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?
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);
}