- Open window in JavaScript with HTML inserted
- 8 Answers 8
- @key-in_short,workaround:: [for cross-origin access exception ]
- @details::
- @problem-given_situation,@problem-arise_problem::
- => @problem-solution-workaround::
- @minor-note::
- Window open()
- See Also:
- Syntax
- Parameters
- Deprecated
- Warning
- Return Value
- More Examples
- Browser Support
- Can I open a new window and populate it with a string variable?
- 5 Answers 5
- HTML
- Opening XML?
Open window in JavaScript with HTML inserted
How would I open a new window in JavaScript and insert HTML data instead of just linking to an HTML file?
8 Answers 8
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).
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";
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?
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.
Also call document.close() after write() in case you have embedded JS event handler as this will trigger DOMContentLoad events.
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.
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:
This is the code, but StackOverflow blocks the window from being opened (see the codepen example instead):
const winHtml = ` Hello from the new window!
`; const winUrl = URL.createObjectURL( new Blob([winHtml], < type: "text/html" >) ); const win = window.open( winUrl, "win", `width=800,height=400,screenX=200,screenY=200` );
Great 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.
This is what I was looking for. This allowed me to use the ‘noopener’ option of window.open to prevent the new window from having access to my main window. Thanks!
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
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 tag
Then open this file using
And add whatever you want to add in your body tag. using following code
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");
Use this one. It worked for me very perfect.
new_window = window.open(URL.createObjectURL(new Blob([HTML_CONTENT], < type: "text/html" >)))
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(["Hello
"], < type: "text/html" >)))
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::
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';
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.
- @eg::
- in your main.html
// #>> open ViewerJs in a new html window eleJq_Img.click(function() < // #>>> send some query string data -- a list of 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'); >);
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.htmlbefore window_ImageGallery.html is loaded
- above 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()
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); >
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 >);
- @minor-comment:: There are too many similar Posts about the cross-origin issue. And there are some posts about window.open() Idk which post is the best place to place the answer. And I picked here.
Window open()
The open() method opens a new browser window, or a new tab, depending on your browser settings and the parameter values.
See Also:
Syntax
Parameters
Deprecated
- true - URL replaces the current document in the history list
- false - URL creates a new entry in the history list
Warning
Chrome throws an exception when using this parameter.
Return Value
More Examples
Open an about:blank page in a new window/tab:
Open a new window called "MsgWindow", and write some text into it:
var myWindow = window.open("", "MsgWindow", "width=200,height=100");
myWindow.document.write("This is 'MsgWindow'. I am 200px wide and 100px tall!
");
Replace the current window with a new window:
var myWindow = window.open("", "_self");
myWindow.document.write("I replaced the current window.
");
Open a new window and control its appearance:
window.open("https://www.w3schools.com", "_blank", "toolbar=yes,scrollbars=yes,resizable=yes,top=500,left=500,width=400,height=400");
Open a new window. Use close() to close the new window:
function openWin() <
myWindow = window.open("", "myWindow", "width=200,height=100"); // Opens a new window
>function closeWin() myWindow.close(); // Closes the new window
>Open a new window. Use the name property to return the name of the new window:
var myWindow = window.open("", "MsgWindow", "width=200,height=100");
myWindow.document.write("This window's name is: " + myWindow.name + "
");
Using the opener property to return a reference to the window that created the new window:
var myWindow = window.open("", "myWindow", "width=200,height=100"); // Opens a new window
myWindow.document.write("This is 'myWindow'
"); // Text in the new window
myWindow.opener.document.write("This is the source window!
"); // Text in the window that created the new window
Browser Support
open() is supported in all browsers:
Chrome Edge Firefox Safari Opera IE Yes Yes Yes Yes Yes Yes Can I open a new window and populate it with a string variable?
I am having a bit of a battle with something that seems simple. I have a [javascript] string that has DOM elements in it and would like to open a new window (window.open()?) and use the string the populate the new window. i.e. have the browser take the string and convert it into HTML on the fly. Is this possible?
5 Answers 5
var wnd = window.open("about:blank", "", "_blank"); wnd.document.write(html);
I'm trying to instantiate a blank page in a new tab with a pre-populated script which waits for the blank page in the new tab to finish being instantiated and then displays an alert on the blank page in the new tab saying something like 'success'. Everything I've tried so far either displays the alert in the current tab, instantiating the blank page in a new tab only after addressing the alert -or else the blank page in the new tab and the alert are instantiated/displayed simultaneously, with the alert still appearing only outside of the blank page in the new tab.
Note that browsers have locked down window.open a lot since 2013, and the better approach these days is to to use a link element with an appropriate data-uri (see below)
HTML
Archer's answer is a good one, but you can do this in a one liner if you wish:
window.open("data:text/html;charset=utf-8,"+html, "", "_blank")
Opening XML?
window.open("data:text/xml;charset=utf-8,"+xml, "", "_blank")
With XML, make sure you string begins with and has a root element. If it doesn't, you can easily add it:
window.open('data:text/xml;charset=utf-8,
'+xml+' ', "", "_blank")Archer's answer is the best way. But you need to close the document to run the scripts inside the "htmlString".
var wnd = window.open("about:blank", ""); wnd.document.write(htmlString); wnd.document.close();
If you need in new tab you can use this.
const win = window.open('about:blank', '_blank'); win.document.write('
test
'); win.focus();Note that while window.open was a good solution in 2013, at this point in time that is no longer the case, and window.open is not the right answer here anymore; it has become blocked-by-default by almost every browser due to years of abuse by ads, and is frowned upon as a legacy mechanism that completely bypasses the browser history when it does work.
Instead, build a link anchor element, assign its content as a data-uri, give it a target="_blank" so that it'll open in a new tab, and then trigger a click() on it so that it opens that content as a normal webpage with a normal entry in the browser's history:
function openAsPageInNewTab(pageContent) < let encoded = encodeURIComponent(pageContent); let a = document.createElement(`a`); a.target = `_blank`; a.href = `data:text/html;charset=utf-8,$`; a.style.display = `none`; document.body.appendChild(a); // We need to do this, a.click(); // so that we can do this, document.body.removeChild(a); // after which we do this. >
You might of course still get a popup warning, because it should, but at least you're now doing things in a way that respects users and browsers, unlike the legacy window.open approach.
- due to, if you modify the html of 'window_ImageGallery.html' in main.htmlbefore window_ImageGallery.html is loaded