To prepare the entire document in advance of opening it, one option is through a data URI or an Object URL that points to a Blob.
// Utilizing Blob method which is more modern with minimal restrictions
function createWindow(code) {
var blob = new Blob([code], {type: 'text/html'}),
url = URL.createObjectURL(blob),
win = window.open(url, '_blank');
URL.revokeObjectURL(url); // cleanup
return win;
}
createWindow('\
<!doctype html>\n\
<html>\n\
<head>\n\
<title>Hello World!</title>\n\
</head>\n\
<body>\n\
<span>Foobar</span>\n\
</body>\n\
</html>\n\
');
Alternatively, you can also use this approach:
// Employing data URI method, which has more limitations but is compatible with older browsers
function createWindow2(code) {
return window.open('data:text/html,' + window.encodeURIComponent(code), '_blank');
}
createWindow2('\
<!doctype html>\n\
<html>\n\
<head>\n\
<title>Hello World!</title>\n\
</head>\n\
<body>\n\
<span>Fizzbuzz</span>\n\
</body>\n\
</html>\n\
');