javascript - 将 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 ,但我认为它不会像直接使用引用那样优化。
解决方案
推荐阅读
- node.js - 使用 React 和 Express GraphQL 的频繁请求
- rust - 我应该如何在 Rust 中输入 annotate collect() (error[E0282])?
- java - 无法将裸骨 webapp 部署到运行 openjdk 11 的 tomee 7.1.0
- python - 在 Xcode 中运行 python 文件会出现以下错误:Command ExternalBuildToolExecution failed with a nonzero exit code
- php - 如何在段落中添加阅读更多
- artificial-intelligence - 后跳、CSP、AIMA 书
- android - cookie 未在 web 视图中设置
- reactjs - TimeoutException: Asp.net Core 2.2 with react ,请求超时时间为 50 秒
- python - 模块导入仅在 docker 中失败
- sql-server - 发布项目的 asp.net MVC 问题 - 创建数据库权限被拒绝