Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to overwrite a function using a userscript?

I want to change parts of the webpage display, is it possible to overwrite a function with a userscript?

Below is the function I would like overwritten (also found Here):

function StartDrawing() {
    if ((typeof (systemsJSON) != "undefined") && (systemsJSON != null)) {
        var stellarSystemsLength = systemsJSON.length;
        $('#mapDiv').empty();
        if (stellarSystemsLength > 0) {
            InitializeRaphael();

            var i = 0;
            for (i = 0; i < stellarSystemsLength; i++){
                var stellarSystem = systemsJSON[i];
                DrawSystem(stellarSystem)
            }
        }
    }
}

This would allow me to run my own drawing algorithms.

How do I do this with a userscript in chromium (or Firefox)?

like image 566
Reactormonk Avatar asked Dec 20 '22 19:12

Reactormonk


1 Answers

See "Accessing Variables (and Functions) from Greasemonkey to Page & vice versa.

Userscripts are separated from the target page, so you can't just overwrite a function or variable without understanding the context...

IF the function is global (looks like it probably is in this case), you can inject your new function definition:

function StartDrawing () {
    // WHATEVER YOU WANT FOR THE NEW CODE GOES HERE.
}

addJS_Node (StartDrawing);

function addJS_Node (text, s_URL, funcToRun, runOnLoad) {
    var D                                   = document;
    var scriptNode                          = D.createElement ('script');
    if (runOnLoad) {
        scriptNode.addEventListener ("load", runOnLoad, false);
    }
    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);
}


This works in almost every browser that supports userscripts.

You may need to delay the load in some cases, by firing on the window load event and/or checking to see if the function already exists.

Depending on your browser, you may have additional options (see the linked Q&A, above):

  • In Firefox+Greasemonkey, you can use @grant none mode or unsafeWindow.
  • In Chrome+Tampermonkey, you can usually use unsafeWindow. @grant none mode probably works too, but I haven't tested it myself.




If the function is NOT global:

Then in Firefox you must overwrite the JS source as it comes in. See "Stop execution of javascript function (client side) or tweak it".

In Chrome you're mostly out of luck (last verified six-ish months ago).

like image 85
Brock Adams Avatar answered Jan 11 '23 09:01

Brock Adams