Log a web page's dynamically-created, DOM elements with a userscript

孤街浪徒 提交于 2019-12-18 09:18:13

问题


I want to extract all the dynamic javascript functions from a web page, with a userscript.

Someone suggested using a hook for DOM objects. They also provided this example:

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


I think this functions logs all the document.createElement() calls, but where do I add this function in my userscript?
I tried creating a userscript which contains only this function, but it did not work.

The userscript gets executed after the page is loaded. How can this function be changed so that it tracks the dynamic functions before hand?


回答1:


To track all dynamically loaded arguments "before hand", use // @run-at document-start.

Also, you must inject the code into the target page, because the page's javascript is what you want to track.

Here is a complete script that logs all createElement() calls. It works with both Greasemonkey (Firefox) and 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);
}


来源:https://stackoverflow.com/questions/10083010/log-a-web-pages-dynamically-created-dom-elements-with-a-userscript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!