首页 > 解决方案 > 将 IFrame 的文档替换为对全局文档的引用

问题描述

我需要创建一个包含一些内容的模式,其中的一些 CSS 会破坏主文档的样式,因此我决定通过将其作为新文档的 iframe 来“沙盒化”模式内容。要仅加载一次特定于模态的 css,我想为所有模态重用同一个文档,并且只替换正文。

我的问题:我使用此代码将全局文档放在 IFrame 中(剥离为仅包含相关部分):

window.newdoc = document.implementation.createHTMLDocument("Menu");
let iframe = document.createElement("iframe");
iframe.src = 'about:blank';
iframe.onload = () => {
    let node = iframe.contentDocument.importNode(newdoc.documentElement, true);
    iframe.contentDocument.replaceChild(node, iframe.contentDocument.documentElement);
}

问题在于它使用importNode克隆我的文档。我想改用全局文档的引用,这样如果我newdoc.body.innerHTML = "some html";稍后再做,它也会更新 iframe 中的文档。我已经尝试过以下操作:

iframe.onload = () => {
    iframe.contentDocument.documentElement = newdoc.documentElement;
}
// And
iframe.onload = () => {
    iframe.contentDocument = newdoc;
}

都没有奏效。有没有办法做到这一点?我考虑过可能MutationObserver为每个 IFrame 使用 a ,但我认为它不会像直接使用引用那样优化。

标签: javascripthtmldomiframe

解决方案


推荐阅读