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?
The open() method opens a new browser window, or a new tab, depending on your browser settings and the parameter values.
Open in a new window To open a link in a new browser window, hold the Shift on then click the link or right-click the link and select Open link in New Window.
Yes it's possible...
var wnd = window.open("about:blank", "", "_blank");
wnd.document.write(html);
That should do the trick.
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")
window.open("data:text/xml;charset=utf-8,"+xml, "", "_blank")
With XML, make sure you string begins with <?xml version="1.0" encoding="UTF-8"?>
and has a root element. If it doesn't, you can easily add it:
window.open('data:text/xml;charset=utf-8,<?xml version="1.0" encoding="UTF-8"?><RootTag>'+xml+'</RootTag>', "", "_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('<h1>test</h1>');
win.focus();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With