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

A. *_*hny 5 javascript anonymous-function userscripts

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';
})();
Run Code Online (Sandbox Code Playgroud)

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

Bro*_*ams 2

是的! 如果您使用正确的浏览器 (Firefox),就可以

在用户脚本(在 Firefox 上)中,您可以重写页面的 JS 以授予您自己访问权限。另请参阅“如何使用 Greasemonkey 更改此 javascript?”

您的函数调用将类似于(对于内联脚本):

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);
}
Run Code Online (Sandbox Code Playgroud)

然后您将访问该变量,如下所示:

console.log ("The var is: ", unsafeWindow.myJS);
Run Code Online (Sandbox Code Playgroud)

唉,仍然没有好方法在Chrome用户脚本或 Tampermonkey 脚本 中执行此类操作。

如果带有相关 JS 的脚本是外部的,那么在 Chrome 中,您可以使用beforeload来阻止它。然后注入您自己的代码——修改为公开该私有变量。