简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM