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 =[
.append()
should also execute it... – LorraineparseHTML()
, it seems to only parse the<head>
for some reason; if you have a working example, please by all means let me see (I could have very easily messed up in testing =P) – Carbonari