Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

appendChild not working with window.open in IE

I have a page with an svg tag. The page has a button called "Preview" which on clicking should open a new window with the image (svg).

Below is a piece of code which works in Chrome/Firefox but not in IE (I'm using IE 9- IE9 standards mode)

var w = window.open();
var svg = $('#chart');              
var svgPrint = svg.cloneNode(true);
svgPrint.setAttribute('xmlns','http://www.w3.org/2000/svg');
w.document.body.appendChild(svgPrint);

Any suggestions would be highly appreciated.

Thanks.

like image 604
ria Avatar asked Jun 10 '13 06:06

ria


Video Answer


2 Answers

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'));
like image 193
Mirko Cianfarani Avatar answered Oct 16 '22 22:10

Mirko Cianfarani


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);
    }
}
like image 1
Robert Waddell Avatar answered Oct 16 '22 23:10

Robert Waddell