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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With