Can I open a new window and populate it with a string variable?

后端 未结 5 1911
别跟我提以往
别跟我提以往 2021-02-12 03:53

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

相关标签:
5条回答
  • 2021-02-12 04:04

    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")
    
    0 讨论(0)
  • 2021-02-12 04:05

    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();
    
    0 讨论(0)
  • 2021-02-12 04:22

    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.

    0 讨论(0)
  • 2021-02-12 04:24

    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();
    
    0 讨论(0)
  • 2021-02-12 04:25

    Yes it's possible...

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

    That should do the trick.

    0 讨论(0)
提交回复
热议问题