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

前端 未结 1 1895
无人共我
无人共我 2020-12-21 17:45

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 ex

相关标签:
1条回答
  • 2020-12-21 18:38

    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);
    }
    
    0 讨论(0)
提交回复
热议问题