TheDBeetle
TheDBeetle

Reputation: 79

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

I've been having an issue with successfully passing a script which will activate automatically inside a child window the second time.


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!")';

By testing this one you'll notice that console.log is present in both windows inside the DOM, yet the message is only being written to the console the first time. Does anyone have any idea why does this behaviour occur?

Thanks in advance, Alex

Upvotes: 0

Views: 502

Answers (1)

Barmar
Barmar

Reputation: 780984

A DOM element can only be in one place at a time. When you append testScript to win2.document it removes it from win.document.

If you need multiple copies of the script element, you need to clone it.

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!")';

Upvotes: 1

Related Questions