首页 > 解决方案 > MutationObserver - 如何检测 iframe 中的 dom 变化

问题描述

让我先解释一下这个问题:我的脚本有一个突变观察器,它检测添加的节点,并对内容进行一些处理——比如比较和突出显示一些值。当前实现检测整个文档正文的变化,目标看起来像这样

var target = document.querySelector('body');

一切正常,除非有 iframe。有些客户页面有一个 iframe 或多个 iframe,有些则没有。

我的脚本被添加到父文档的脚本标签中。

问题:a) 是否有可能获得相同的 MutationObserver 来检测 body 和 iframe 的变化?即 dom 中的所有内容,包括 iframe b) 如果单个观察者不可能,那么替代方法是什么?

请注意:我的脚本只能转到主/父文档

标签: javascript

解决方案


您需要为每个要观看的 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 的域,那么您就不走运了。


推荐阅读