2012-04-10 83 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