javascript - MutationObserver - 如何检测 iframe 中的 dom 变化
问题描述
让我先解释一下这个问题:我的脚本有一个突变观察器,它检测添加的节点,并对内容进行一些处理——比如比较和突出显示一些值。当前实现检测整个文档正文的变化,目标看起来像这样
var target = document.querySelector('body');
一切正常,除非有 iframe。有些客户页面有一个 iframe 或多个 iframe,有些则没有。
我的脚本被添加到父文档的脚本标签中。
问题:a) 是否有可能获得相同的 MutationObserver 来检测 body 和 iframe 的变化?即 dom 中的所有内容,包括 iframe b) 如果单个观察者不可能,那么替代方法是什么?
请注意:我的脚本只能转到主/父文档
解决方案
您需要为每个要观看的 iframe 设置不同的突变观察器。因此,如果您想在当前文档中使用一个,您还需要一个不同的观察者。
如果您有权访问 iframe,则可以像这样观看它:
// Get the iframe body
let iframe = document.getElementById('my-iframe').document.body
// Setup the config
let config = { attributes: true, childList: true }
// Create a callback
let callback = function(mutationsList) { /* callback actions */ }
// Watch the iframe for changes
let observer = new MutationObserver(callback)
observer.observe(iframe, config)
如果 iframe 位于父级的子域上,您可以在 iframe 中使用它:
// where parent.com is the parent domain of the iframe
document.domain = 'parent.com'
如果您不拥有 iframe 的域,那么您就不走运了。
推荐阅读
- javascript - 为什么我不能将其转换为“指针类型”?所以它可以用于所有 3 种类型“鼠标单击、笔、触摸。非常感谢帮助
- python - VS Code集成终端找不到python的pip3安装包
- cadence-workflow - Cadence Workflow Server 升级(0.12.1 到 0.16.0):是否始终需要运行不受支持的工作流命令?
- sql-server - Laravel Sail 和 SQL 驱动程序
- wordpress - 如何对具有多个标题的列表页面 url 进行排名,例如目录网站?
- java - 如何停止 JGroups TCPPING 尝试将消息发送到静态 initial_hosts 中的丢失节点
- reactjs - .map 堆叠卡片而不是并排放置
- python-3.x - Creating lists with groups of characters with python
- google-chrome-extension - 如何调试谷歌浏览器扩展?
- particle-swarm - 在粒子群优化程序中使用时,keyerror 'micro avg' 无法在 python 中运行