javascript - DOMParser 将 &lt;script&gt; 标签附加到 <head>/<body> 但不执行

标签 javascript domparser

我试图通过 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 节点并将它们呈现在页面上;然而,任何 <script> <head> 中存在的标签或 <body>已解析字符串中的节点无法执行 =[。直接使用 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) 替代方案相反是因为我需要在 postMessage() 中使用它SSL下IE回调; document.write()在 IE 中访问 SSL 页面时在回调事件中被阻止,例如发布消息 =[

最佳答案

你应该使用:

const sHtml = '<script>window.alert("Hello!")</script>';
const frag = document.createRange().createContextualFragment(sHtml)
document.body.appendChild( frag );

关于javascript - DOMParser 将 &lt;script&gt; 标签附加到 <head>/<body> 但不执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22945884/

相关文章:

javascript - CSS 模态窗口闪烁 onload

JavaScript/正则表达式 : Expression works in one environment and not another

javascript - 可以在 Google Chrome 扩展中生成 PDF 吗?

javascript - 为什么我的 XSLTProcessor transformToDocument 不起作用?

java - XML解析、动态结构、内容

javascript - React-Native fetch 不将正文内容发送到 $_POST

javascript - $ ('textarea' ).rows 扩展/收缩

javascript - 是否可以将 domparser 元素更改为字符串?

javascript - 使用 JavaScript 阻止 DOM 解析

javascript - 如果 DOMParser innerHTML 是脚本,则不显示第一个元素