How would I open a new window in JavaScript and insert HTML data instead of just linking to an HTML file?
8 Answers
I would not recomend you to use document.write
as others suggest, because if you will open such window twice your HTML will be duplicated 2 times (or more).
Use innerHTML instead
var win = window.open("", "Title", "toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=yes,resizable=yes,width=780,height=200,top="+(screen.height-400)+",left="+(screen.width-840));
win.document.body.innerHTML = "HTML";
-
4Good idea to use innerHTML! – NilsB Nov 03 '16 at 13:05
-
Will the **body** object be present on a newly created window? – user3245268 Apr 23 '19 at 21:35
-
1Yes, it is always present on any page, even if you don't put it, the browser will auto-add it – artnikpro Apr 24 '19 at 07:52
-
1Please note that if you have – Дамян Станчев Feb 25 '20 at 08:13
-
I am opening the window like this: `var win = window.open("", "Page Help", "newwindow", "width=1100, height=700, top=100, left=100"); win.document.body.innerHTML = "help_text";` But the window is full screen and has no title. Why is it not respecting my settings? – Larry Martell Aug 18 '20 at 23:44
-
@LarryMartell Try using the [`
`](https://www.w3schools.com/tags/tag_title.asp) tag inside `win.document.head.innerHTML` – Nanoo Oct 01 '20 at 17:54 -
@LarryMartell you're using the API wrong. See https://developer.mozilla.org/en-US/docs/Web/API/Window/open .. it takes 3 parameters, and perhaps you don't understand the second one. Often, '_blank' is used in this case but you can use any string and running the same code a second time will refer to the previously opened window. `var win = window.open("", "newwindow", "width=1100, height=700, top=100, left=100"); win.document.body.innerHTML = "
This is the title help_text";` works for me. – Neek Feb 09 '21 at 04:39 -
Using `width=780,height=200` makes it harder to adapt to different screen sizes. Something like `width=50%, height=20%` (if that was your thinking for 1920x1080 footprint) would be better. Just not sure how that is coded for the `window.open` function/method. In the same vein, `top="+(screen.height-400)+",left="+(screen.width-840)` would be problematic. – WinEunuuchs2Unix Feb 05 '22 at 01:01
You can use window.open to open a new window/tab(according to browser setting) in javascript.
By using document.write you can write HTML content to the opened window.

- 184,426
- 49
- 232
- 263
-
1Also call `document.close()` after `write()` in case you have embedded JS event handler as this will trigger DOMContentLoad events. – zirkelc Aug 08 '21 at 17:27
When you create a new window using open
, it returns a reference to the new window, you can use that reference to write to the newly opened window via its document
object.
Here is an example:
var newWin = open('url','windowName','height=300,width=300');
newWin.document.write('html to write...');
Here's how to do it with an HTML Blob, so that you have control over the entire HTML document:
https://codepen.io/trusktr/pen/mdeQbKG?editors=0010
This is the code, but StackOverflow blocks the window from being opened (see the codepen example instead):
const winHtml = `<!DOCTYPE html>
<html>
<head>
<title>Window with Blob</title>
</head>
<body>
<h1>Hello from the new window!</h1>
</body>
</html>`;
const winUrl = URL.createObjectURL(
new Blob([winHtml], { type: "text/html" })
);
const win = window.open(
winUrl,
"win",
`width=800,height=400,screenX=200,screenY=200`
);

- 44,284
- 53
- 191
- 263
-
2Great solution, this really helped me out on a project where adding in an extra HTML file for the new window content would have been problematic. Just to add that it's worth including `` in the `` of your HTML to ensure it will render any non-Latin characters. – moloko Jul 13 '21 at 13:19
You can open a new popup window by following code:
var myWindow = window.open("", "newWindow", "width=500,height=700");
//window.open('url','name','specs');
Afterwards, you can add HTML using both myWindow.document.write();
or myWindow.document.body.innerHTML = "HTML";
What I will recommend is that first you create a new html file with any name. In this example I am using
newFile.html
And make sure to add all content in that file such as bootstrap cdn or jquery, means all the links and scripts. Then make a div with some id or use your body and give that a id
. in this example I have given id="mainBody"
to my newFile.html <body>
tag
<body id="mainBody">
Then open this file using
<script>
var myWindow = window.open("newFile.html", "newWindow", "width=500,height=700");
</script>
And add whatever you want to add in your body tag. using following code
<script>
var myWindow = window.open("newFile.html","newWindow","width=500,height=700");
myWindow.onload = function(){
let content = "<button class='btn btn-primary' onclick='window.print();'>Confirm</button>";
myWindow.document.getElementById('mainBody').innerHTML = content;
}
myWindow.window.close();
</script>
it is as simple as that.

- 27,509
- 17
- 111
- 155

- 111
- 1
- 3
You can also create an "example.html" page which has your desired html and give that page's url as parameter to window.open
var url = '/example.html';
var myWindow = window.open(url, "", "width=800,height=600");

- 401
- 3
- 9
Use this one. It worked for me very perfect.
For New window:
new_window = window.open(URL.createObjectURL(new Blob([HTML_CONTENT], { type: "text/html" })))
for pop-up
new_window = window.open(URL.createObjectURL(new Blob([HTML_CONTENT], { type: "text/html" })),"width=800,height=600")
Replace HTML_CONTENT with your own HTML Code Like:
new_window = window.open(URL.createObjectURL(new Blob(["<h1>Hello</h1>"], { type: "text/html" })))

- 1
- 1
if your window.open()
& innerHTML
works fine, ignore this answer.
following answer only focus on cross-origin access exception
@key-in_short,workaround:: [for cross-origin access exception
]
when you exec code in main.html
-- which tries to access file window_ImageGallery.html
by using window.open()
& innerHTML
for anyone who encounter cross-origin access exception
and you dont want to disable/mess_around_with Chrome security policy
-> you may use query string to transfer the html code data, as a workaround.
@details::
@problem-given_situation,@problem-arise_problem::
say you exec following simple
window.open
command as other answer suggested.let window_Test = window.open('window_ImageGallery.html', 'Image Enlarged Window' + $(this).attr('src'), 'width=1000,height=800,top=50,left=50'); window_Test.document.body.innerHTML = 'aaaaaa';
you may encounter following
cross-origin access exception
window_Test.document.body.innerHTML = 'aaaaaa'; // < Exception here Uncaught DOMException: Blocked a frame with origin "null" from accessing a cross-origin frame.
=> @problem-solution-workaround::
you may use query string to transfer the html code data, as a workaround. <- Transfer data from one HTML file to another
@eg::
in your
main.html
// #>> open ViewerJs in a new html window eleJq_Img.click(function() { // #>>> send some query string data -- a list of <img> tags, to the new html window // @repeat: must use Query String to pass html code data, else you get `Uncaught DOMException: Blocked a frame with origin "null" from accessing a cross-origin frame.` (cross origin access issue) let id_ThisImg = this.id; let ind_ThisImg = this.getAttribute('data-index-img'); let url_file_html_window_ImageGallery = 'window_ImageGallery.html' + '?queryStr_html_ListOfImages=' + encodeURIComponent(html_ListOfImages) + '&queryStr_id_ThisImg=' + encodeURIComponent(id_ThisImg) + '&queryStr_ind_ThisImg=' + encodeURIComponent(ind_ThisImg); // #>>> open ViewerJs in a new html window let window_ImageGallery = window.open(url_file_html_window_ImageGallery, undefined, 'width=1000,height=800,top=50,left=50'); });
in your
window_ImageGallery.html
window.onload = function () { // #>> get parameter from URL // @repeat: must use Query String to pass html code data, else you get `Uncaught DOMException: Blocked a frame with origin "null" from accessing a cross-origin frame.` (cross origin access issue) // https://stackoverflow.com/questions/17502071/transfer-data-from-one-html-file-to-another let data = getParamFromUrl(); let html_ListOfImages = decodeURIComponent(data.queryStr_html_ListOfImages); let id_ThisImgThatOpenedTheHtmlWindow = decodeURIComponent(data.queryStr_id_ThisImg); let ind_ThisImgThatOpenedTheHtmlWindow = decodeURIComponent(data.queryStr_ind_ThisImg); // #>> add the Images to the list document.getElementById('windowImageGallery_ContainerOfInsertedImages').innerHTML = html_ListOfImages; // -------- do your stuff with the html code data }; function getParamFromUrl() { let url = document.location.href; let params = url.split('?')[1].split('&'); let data = {}; let tmp; for (let i = 0, l = params.length; i < l; i++) { tmp = params[i].split('='); data[tmp[0]] = tmp[1]; } return data }
@minor-note::
(seems) sometimes you may not get the
cross-origin access exception
due to, if you modify the html of 'window_ImageGallery.html' in
main.html
beforewindow_ImageGallery.html
is loadedabove statement is based on my test
& another answer -- window.open: is it possible open a new window with modify its DOM
if you want to make sure to see that Exception,
you can try to wait until the opening html window finish loading, then continue execute your code
@eg::
use defer() <- Waiting for child window loading to complete
let window_ImageGallery = window.open('window_ImageGallery.html', undefined, 'width=1000,height=800,top=50,left=50'); window_ImageGallery.addEventListener("unload", function () { defer(function (){ console.log(window_ImageGallery.document.body); // < Exception here }); }); function defer (callback) { var channel = new MessageChannel(); channel.port1.onmessage = function (e) { callback(); }; channel.port2.postMessage(null); }
or use
sleep()
withasync
What is the JavaScript version of sleep()?eleJq_Img.click(async function() { ... let window_Test = window.open( ... ... await new Promise(r => setTimeout(r, 2000)); console.log(window_Test.document.body.innerHTML); // < Exception here });
or you get
null
pointer exceptionif you try to access elements in
window_ImageGallery.html
@minor-comment::
There are too many similar Posts about the
cross-origin
issue. And there are some posts aboutwindow.open()
Idk which post is the best place to place the answer. And I picked here.

- 555
- 1
- 5
- 13