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

后端 未结 5 1912
别跟我提以往
别跟我提以往 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: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.

提交回复
热议问题