JavaScript window.open,将脚本传递给 child window 只能使用一次

JavaScript window.open, passing scripts to child window only works once

我在成功传递脚本时遇到了问题,该脚本将在 child window 第二次自动激活。


let win = undefined;
let win2 = undefined;
let testInterval = setInterval(function(){
    if(win === undefined){
        win = window.open("?");
        win.document.body.appendChild(testScript);
        listenToMessages();
    }else{
        if(win.closed === true){
            win = window.open("?");
            win.document.body.appendChild(testScript);
            listenToMessages();
        }
    }
    if(win2 === undefined){
        win2 = window.open("?");
        win2.document.body.appendChild(testScript);
        listenToMessages();
    }else{
        if(win2.closed === true){
            win2 = window.open("?");
            win2.document.body.appendChild(testScript);
            listenToMessages();
        }
    }
}, 2000);

let testScript = document.createElement('script');
testScript.textContent = 'console.log("here!")';

通过测试这个,您会注意到 console.log 出现在 DOM 内的两个 windows 中,但消息仅在第一次写入控制台。 有谁知道为什么会出现这种行为?

提前致谢, 亚历克斯

一个DOM元素一次只能出现在一个地方。当您将 testScript 附加到 win2.document 时,它会将其从 win.document.

中删除

如果您需要 script 元素的多个副本,则需要克隆它。

let win = undefined;
let win2 = undefined;
let testInterval = setInterval(function() {
  if (!win || win.closed) {
    win = window.open("?");
    if (win) {
      win.document.body.appendChild(testScript);
      listenToMessages();
    } else {
      console.log("Unable to open win");
    }
  }
  if (!win2 || win2.closed) {
    win2 = window.open("?");
    if (win2) {
      let testScript2 = testScript.cloneNode();
      win2.document.body.appendChild(testScript2);
      listenToMessages();
    } else {
      console.log("Unable to open win2");
    }
  }
}, 2000);

let testScript = document.createElement('script');
testScript.textContent = 'console.log("here!")';