[英]MutationObserver - how to detect dom changes within iframe
Let me first explain the problem: My script has a mutationobserver, which detects added nodes, and does some processing on the content - like compare and highlight some values.让我先解释一下这个问题:我的脚本有一个突变观察器,它检测添加的节点,并对内容进行一些处理——比如比较和突出显示一些值。 The current implementation detects changes in the entire document body, the target looks like this
当前实现检测整个文档正文的变化,目标看起来像这样
var target = document.querySelector('body');
Everything works well, except when there is an iframe.一切正常,除非有 iframe。 Some client pages have an iframe or multiple iframes, others do not.
有些客户页面有一个 iframe 或多个 iframe,有些则没有。
My script is added within a script tag in the parent document.我的脚本被添加到父文档的脚本标签中。
Question: a) is it possible to get the same MutationObserver to detect changes in body and iframe ?问题:a) 是否有可能获得相同的 MutationObserver 来检测 body 和 iframe 的变化? ie everything in the dom including the iframe b) if it is not possible with a single observer, what is the alternate method?
即 dom 中的所有内容,包括 iframe b) 如果单个观察者不可能,那么替代方法是什么?
please note: my script can only go to the main/parent document请注意:我的脚本只能转到主/父文档
You will need to have a different mutationobserver for each iframe that you want to watch.您需要为每个要观看的 iframe 设置不同的突变观察器。 So if you want one on the current document you will also need a different observer there as well.
因此,如果您想在当前文档中使用一个,您还需要一个不同的观察者。
If you have access to the iframe, you can then watch it like so:如果您有权访问 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)
If the iframe is on a sub-domain of the parent you can use this in the iframe:如果 iframe 位于父级的子域上,您可以在 iframe 中使用它:
// where parent.com is the parent domain of the iframe
document.domain = 'parent.com'
Note: document.domain
is now deprecated.注意:
document.domain
现在已弃用。
If you do not own the domain of the iframe you're out of luck.如果您不拥有 iframe 的域,那么您就不走运了。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.