我试图通过 DOMParser 将一个字符串解析为一个完整的 HTML 文档,然后用处理过的节点覆盖当前页面。 该字符串包含完整的标记,包括<!doctype>
、 <html>
、 <head>
和<body>
节点。
// 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;
这是因为它成功地获取了已解析的 HTML 节点并将它们呈现在页面上; 但是,解析字符串内的<head>
或<body>
节点中存在的任何<script>
标记都无法执行 =[。 直接使用html
标签(与head
/ body
相对)进行测试会产生相同的结果。
我也尝试过使用.appendChild()
而不是.innerHTML()
,但没有改变:
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]);
有谁知道将字符串转换为完整的 HTML 页面并执行其中包含的 javascript 的方法吗?
如果有替代 DOMParser 的方法可以提供相同的结果(例如覆盖整个文档),请随时推荐它/它们 =]
注意:
我使用它而不是更简单的document.write(data)
替代方案的原因是因为我需要在 SSL 下的 IE 中的postMessage()
回调中使用它; document.write()
在 IE 中访问 SSL 页面时在回调事件中被阻止,例如发布消息 =[