Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 538
arcaderob Avatar asked Jul 05 '13 16:07

arcaderob


People also ask

What is the syntax for opening a new window?

The open() method opens a new browser window, or a new tab, depending on your browser settings and the parameter values.

How do I make a link open in a new window?

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.


4 Answers

Yes it's possible...

var wnd = window.open("about:blank", "", "_blank");
wnd.document.write(html);

That should do the trick.

like image 52
Reinstate Monica Cellio Avatar answered Oct 22 '22 10:10

Reinstate Monica Cellio


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 <?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")
like image 41
Kevin Jantzer Avatar answered Oct 22 '22 12:10

Kevin Jantzer


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();
like image 5
livin tamil Avatar answered Oct 22 '22 10:10

livin tamil


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();
like image 5
Ilya Kyrylov Avatar answered Oct 22 '22 10:10

Ilya Kyrylov