Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I have access to anonymous function variables in a userscript?

I'm looking for modify a javascript game with an userscript.

The problem is that all the game code is wrapped with a anonymous function like this

(function () { "use strict";
    var js = 'test';
})();

Can I have access to a JS variable with my userscript?

Edit :

See also : How to alter this javascript with Greasemonkey?

This question is not the same as Is it possible to gain access to the closure of a function? !

like image 315
A. Joahny Avatar asked Nov 14 '13 18:11

A. Joahny


1 Answers

Yes! You can if you use the right browser (Firefox).

In a userscript (on Firefox) you can rewrite the page's JS to give yourself access. See, also, "How to alter this javascript with Greasemonkey?".

Your function call would be like (for an inline script):

checkForBadJavascripts ( [
    [false, /js = 'test'/, replaceTargetJavascript]
] );


function replaceTargetJavascript (scriptNode) {
    var scriptSrc   = scriptNode.textContent;
    scriptSrc       = scriptSrc.replace (
        /js = 'test';/,
        "js = 'test'; window.myJS = js;"
    );

    addJS_Node (scriptSrc);
}

You would then access the variable like:

console.log ("The var is: ", unsafeWindow.myJS);

Alas, there is still no good way to do this kind of thing in a Chrome userscript or a Tampermonkey script.

IF the script, with the JS in question, is external, then in Chrome, you can use beforeload to block it. Then inject your own code instead -- modified to expose that private variable.

like image 151
Brock Adams Avatar answered Sep 30 '22 03:09

Brock Adams