MutationObserver - 如何检测 iframe 中的 dom 变化

maX*_*maX 11 javascript

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

var target = document.querySelector('body');
Run Code Online (Sandbox Code Playgroud)

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

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

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

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

Get*_*awn 12

您需要为每个要观看的 iframe 设置不同的mutationobserver。因此,如果您想在当前文档中使用一个,您还需要一个不同的观察者。

如果您有权访问 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)
Run Code Online (Sandbox Code Playgroud)

如果 iframe 在父域的子域中,您可以在 iframe 中使用它:

// where parent.com is the parent domain of the iframe
document.domain = 'parent.com'
Run Code Online (Sandbox Code Playgroud)

如果您不拥有 iframe 的域,那您就不走运了。

  • 没有工作/对我来说不可靠,直到我将 `iframe` 更改为 `document.getElementById('my-iframe').contentWindow.document.body` 并将 `subtree:true` 添加到 `config` 变量中。 (9认同)