Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DOMParser appending <script> tags to <head>/<body> but not executing

I'm attempting to parse a string into a full HTML document via DOMParser and then overwrite the current page with the processed nodes. The string contains complete markup, including the <!doctype>, <html>, <head> and <body> nodes.

// parse the string into a DOMDocument element:
var parser = new DOMParser();
var doc = parser.parseFromString(data, 'text/html');

// set the parsed head/body innerHTML contents into the current page's innerHTML
document.getElementsByTagName('head')[0].innerHTML = doc.getElementsByTagName('head')[0].innerHTML;
document.getElementsByTagName('body')[0].innerHTML = doc.getElementsByTagName('body')[0].innerHTML;

This works in that it successfully takes the HTML nodes that were parsed and renders them on the page; however, any <script> tags that exist in either the <head> or <body> nodes inside the parsed string fail to execute =[. Testing directly with the html tag (opposed to head / body) yields the same result.

I've also tried to use .appendChild() instead of .innerHTML() too, but no change:

var elementHtml = document.getElementsByTagName('html')[0];

// remove the existing head/body nodes from the page
while (elementHtml.firstChild) elementHtml.removeChild(elementHtml.firstChild);

// append the parsed head/body tags to the existing html tag
elementHtml.appendChild(doc.getElementsByTagName('head')[0]);
elementHtml.appendChild(doc.getElementsByTagName('body')[0]);

Does anyone know of a way to convert a string to a full HTML page and have the javascript contained within it execute?

If there is an alternative to DOMParser that gives the same results (e.g. overwriting the full document), please feel free to recommend it/them =]

Note:
The reason I'm using this opposed to the much more simple alternative of document.write(data) is because I need to use this in a postMessage() callback in IE under SSL; document.write() is blocked in callback events such as post messages when accessing an SSL page in IE =[

like image 519
newfurniturey Avatar asked Apr 08 '14 18:04

newfurniturey


1 Answers

You should use:

const sHtml = '<script>window.alert("Hello!")</script>';
const frag = document.createRange().createContextualFragment(sHtml)
document.body.appendChild( frag );
like image 179
marciowb Avatar answered Sep 23 '22 17:09

marciowb