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? !

有帮助吗?

解决方案

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.

其他提示

No you cannot access variables that are in a private scope.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top