簡體   English   中英

MutationObserver - 如何檢測 iframe 中的 dom 變化

[英]MutationObserver - how to detect dom changes within iframe

讓我先解釋一下這個問題:我的腳本有一個突變觀察器,它檢測添加的節點,並對內容進行一些處理——比如比較和突出顯示一些值。 當前實現檢測整個文檔正文的變化,目標看起來像這樣

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'

注意: document.domain現在已棄用。

如果您不擁有 iframe 的域,那么您就不走運了。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM