Skip to content Skip to sidebar Skip to footer

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 us

Solution 1:

Yes it's possible...

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

That should do the trick.


Solution 2:

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

Solution 3:

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

Solution 4:

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

Solution 5:

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.


Post a Comment for "Can I Open A New Window And Populate It With A String Variable?"