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

问题描述 投票:0回答:1

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

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

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

我的脚本添加到父文档的脚本标记内。

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

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

javascript
1个回答
20
投票

对于您想要观看的每个 iframe,您将需要有一个不同的mutationobserver。因此,如果您想要当前文档中的一个观察员,您还需要一名不同的观察员。

如果您有权访问 iframe,则可以像这样观看:

// Get the iframe body
//let iframe = document.getElementById('my-iframe').document.body // obsolete
// Edit 2024: (See Update note below)
// Use HTMLIFrameElement.contentDocument property instead:
let iframe = document.getElementById('my-iframe').contentDocument.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'
// Edit: Note that iframe.contentDocument.domain returns the
// iframe's parent domain, if both are Same Origin.

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

注意:

document.domain
现已弃用。

更新(2024):

HTMLIFrameElement API 提供

contentDocument
属性,如果 iframe 和 iframe 的父文档同源,则返回 iframe 的文档。在这种情况下,
contentDocument.domain
does 提供 iframe 父级的域。 这在所有主要浏览器中都有效,除了 IE < 8 and Opera < 12.

参见:

© www.soinside.com 2019 - 2024. All rights reserved.