2012-04-10 43 views
2

我想使用userscript從網頁中提取所有動態javascript函數。使用userscript記錄網頁的動態創建的DOM元素

有人建議爲DOM對象使用鉤子。他們還提供了下面這個例子:

var f = document.createElement;document.createElement = function(tagName){ 
console.log(tagName); 
f.apply(document, arguments); } 


我覺得這個功能會記錄所有的document.createElement()電話, 但我在哪裏,我userscript添加這個功能呢?
我試圖創建一個只包含這個函數的用戶腳本,但它沒有工作。

userscript在加載頁面後執行。如何改變這個功能,以便它能夠事先跟蹤動態功能?

回答

2

要「事先跟蹤」所有動態載入的參數,請使用// @run-at document-start

此外,您必須將代碼注入目標頁面,因爲頁面的JavaScript是您想要跟蹤的。

這是一個完整的腳本,可記錄所有createElement()調用。它的工作原理與兩個的Greasemonkey(火狐)和Chrome userscripts:

// ==UserScript== 
// @name  _Track dynamically added elements 
// @namespace Your PC 
// @include  http://YOUR_SERVER/YOUR_PATH/* 
// @run-at  document-start 
// ==/UserScript== 

//--- Intercept and log document.createElement(). 
function LogNewTagCreations() { 
    var oldDocumentCreateElement = document.createElement; 

    document.createElement   = function (tagName) { 
     var elem = oldDocumentCreateElement.apply (document, arguments); 
     console.log ("Dynamically created a(n)", tagName, " tag. Link: ", elem); 
     return elem; 
    } 
} 

/*--- The userscript or GM script will start running before the DOM is available. 
    Therefore, we wait... 
*/ 
var waitForDomInterval = setInterval (
    function() { 
     var domPresentNode; 
     if (typeof document.head == "undefined") 
      domPresentNode = document.querySelector ("head, body"); 
     else 
      domPresentNode = document.head; 
     if (domPresentNode) { 
      clearInterval (waitForDomInterval); 
      addJS_Node (null, null, LogNewTagCreations); 
     } 
    }, 
    1 
); 

//--- Handy injection function. 
function addJS_Node (text, s_URL, funcToRun) { 
    var D         = document; 
    var scriptNode       = D.createElement ('script'); 
    scriptNode.type       = "text/javascript"; 
    if (text)  scriptNode.textContent = text; 
    if (s_URL)  scriptNode.src   = s_URL; 
    if (funcToRun) scriptNode.textContent = '(' + funcToRun.toString() + ')()'; 

    var targ = D.getElementsByTagName ('head')[0] || D.body || D.documentElement; 
    targ.appendChild (scriptNode); 
} 
+0

謝謝你這麼多,你能解釋一下這個更清楚我寫這userscript並在Firefox安裝,但沒有任何印刷Web控制檯上,你可以幫我這個 – user1275375 2012-04-10 06:21:44

+0

你是否爲你感興趣的網站改變了'http:// YOUR_SERVER/YOUR_PATH/*'爲一些有意義的值?你正在使用什麼版本的Greasemonkey。如果頁面實際上沒有實際創建節點,腳本將不會記錄任何內容。鏈接到目標頁面。 – 2012-04-10 06:24:36

+0

我希望這爲我查看的每個網站我可以刪除@include – user1275375 2012-04-10 06:26:44