2015-10-31 39 views
0

我需要監聽iframe標籤內的更改。主頁面不會更改,只有iframe內容。在iframe中監聽DOM更改

Iframe頁面有形式,當某些按鈕類型提交時單擊窗體調用動作並僅在iframe內更改頁面。

然後我探測,但只能用文件主頁,只有主頁文件監聽DOM變化,而不是在iframe裏面。

function listener() 
{ 
    console.debug("listener fired."); 
} 

document.addEventListener('DOMSubtreeModified', function() { 
    var iframes = document.getElementsByTagName("iframe"); 
    for (var i = 0, len = iframes.length, doc; i < len; ++i) { 
    // Catch and ignore errors caused by iframes from other domains 
    console.log(i); 
    try { 
     doc = iframes[i].contentDocument || iframes[i].contentWindow.document; 
     //console.log(doc); 
     doc.addEventListener("DOMSubtreeModified", listener, true); 
    } catch (ex) { console.log(ex); } 
} 
},false); 
+0

那麼會發生什麼?你有訪問內部框架? – charlietfl

+0

我沒有在iframe頁面上訪問,因爲編譯.aspx頁面,這就是爲什麼我需要使用chrome擴展來完成。 – pinguik

+1

我認爲唯一的選擇是注入一個腳本元素與檢測到iframe中的變化*的代碼。請參閱[構建Chrome擴展 - 使用內容腳本在頁面中注入代碼](https://stackoverflow.com/q/9515704),BTW不使用DOMSubtreeModified,由於速度緩慢,已棄用數年。使用[MutationObserver](https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver)或基於計時器的檢查; – wOxxOm

回答

0

我已經找到了解決方案,與谷歌擴展API我內容腳本和背景之間的頁面只是使用的通訊,然後每一個變化在網頁中做到了,後臺頁面發送到內容腳本的消息然後重新加載內容腳本,讓我評估我在網頁中需要什麼。後臺頁面對我來說是最好的解決方案,因爲它始終處於活動狀態

背景頁

chrome.tabs.onUpdated.addListener(function (tabId, changeInfo, tab) {   
    if (changeInfo.status == 'complete') { 
     chrome.tabs.query({active: true, currentWindow: true}, function(tabs){ 
     chrome.tabs.sendMessage(tabs[0].id, {action: "doit"}, function(response) {}); 
     }); 
    } 
}); 

內容腳本

chrome.extension.onMessage.addListener(function(msg, sender, sendResponse) { 
    if (msg.action == 'doit') { 
     analize_with_content_script(); 
    } 
}); 

analize_with_content_script()是觸發從背景頁收到消息後的功能。

請記住需要在清單文件中聲明背景頁