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 ( 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?


Yes it's possible...

var wnd ="about:blank", "", "_blank");

That should do the trick.


Archer's answer is a good one, but you can do this in a one liner if you wish:"data:text/html;charset=utf-8,"+html, "", "_blank")

Opening XML?"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:'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 ="about:blank", "");

Note that while was a good solution in 2013, at this point in time that is no longer the case, and 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`); = `_blank`;
  a.href = `data:text/html;charset=utf-8,${encoded}`; = `none`;
  document.body.appendChild(a); // We need to do this,;                    // 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 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...