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?

Answers


Yes it's possible...

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

That should do the trick.


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")

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();

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,${encoded}`;
  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.


Need Your Help

Angular 2: Get Values of Multiple Checked Checkboxes

json forms checkbox angular angular2-forms

My problem is really simple: I have a list of checkboxes like this:

Why do you need $ when accessing array and hash elements in Perl?

perl arrays hash sigils

Since arrays and hashes can only contain scalars in Perl, why do you have to use the $ to tell the interpreter that the value is a scalar when accessing array or hash elements? In other words, assu...