appendChild not working with window.open in IE

与世无争的帅哥 提交于 2019-11-27 23:03:44
Mirko Cianfarani

IE will block appending any element created in a different window context from the window context that the element is being appending to.

var childWindow = window.open('somepage.html');

//will throw the exception in IE
childWindow.document.body.appendChild(document.createElement('div'));

//will not throw exception in IE
childWindow.document.body.appendChild(childWindow.document.createElement('div'));
Robert Waddell

After dealing with the same issue, this is an excerpt of the solution that worked in my case for IE, avoiding the SCRIPT5022 error. Thanks to help from this post.

var myWindow = window.open('about:blank', 'loading...', '');
var myWindowDoc = myWindow.document.implementation.createDocument('http://www.w3.org/1999/xhtml', 'html', null);
var myWindowBody = myWindow.document.createElementNS('http://www.w3.org/1999/xhtml', 'body');

myWindow.document.open().write('<html><head></head><body><div id="targetDiv"></div></body></html>');
myWindow.document.close();

try {
    myWindow.document.getElementById('targetDiv').appendChild(HTMLpayload.cloneNode(true)); 
} catch (e){
    if (HTMLpayload.outerHTML) {
        myWindow.document.getElementById('targetDiv').innerHTML = HTMLpayload.outerHTML;
    } else {
        console.log(e);
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!