2016-02-14 41 views
0

Chrome內容腳本能夠訪問頁面的元素。目前,我使用以下代碼來閱讀段落標籤之間的所有文本:每當請求資源時運行Chrome內容腳本

$(document).ready(function(){ 
    $("p").each(function(){ 
     console.log($(this).text()); 
    }); 
}) 

該代碼將返回所有文本。但是,在內容不斷更新的Facebook等頁面中,以後引入的段落不會被記錄。

我在Facebook上注意到,每當我滾動到頁面底部時,都會加載一個包含名爲LitestandMoreStoriesPagelet的附加文本的文檔。有沒有辦法在擴展中實現這樣的請求(或任何有關此事的請求),然後調用javascript函數記錄文本?

我的第一次嘗試將我引向了這個question,但我認爲這不是相關的,因爲它與標籤更改時相關,而不是資源加載時。

+1

如果你想「檢測」 XMLHttpRequest的 - [chrome.webRequest(https://developer.chrome.com/extensions/webRequest)將要走的路 - 這是在答覆中提到關於你連接 –

+0

我看到的問題。我完全掩飾了那部分。謝謝 – Abundance

+0

我相信你也可以使用[.ajaxComplete()](http://api.jquery.com/ajaxcomplete/)jquery函數。 – magreenberg

回答

0

隨着Steve B對MutationObserver的深入瞭解,我能夠輸入以下代碼。大部分代碼的靈感來源於這個link。我需要改變的唯一主要事情是觀察者配置下的subtree: true(因爲我想在所有級別上進行遞歸)。

// The node to be monitored 
var target = $("body,html"); 

// Create an observer instance 
var observer = new MutationObserver(function(mutations) { 
    mutations.forEach(function(mutation) { 
    var newNodes = mutation.addedNodes; // DOM NodeList 
    if(newNodes !== null) { // If there are new nodes added 
     console.log("TRIGGERED"); 
     var $nodes = $(newNodes); // jQuery set 
     $nodes.each(function() { 
      var $node = $(this); 
      var $paragraphs = $node.find("p"); 
      $paragraphs.each(function(){ 
       console.log($(this).text()); 
      }); 
     }); 
    } 
}); 
}); 

// Configuration of the observer: 
var config = { 
    attributes: true, 
    childList: true, 
    characterData: true, 
    subtree: true 
}; 

console.log(target[0].childNodes); 

// Pass in the target node, as well as the observer options 
observer.observe(target[0], config);