我可以访问用户脚本中的匿名函数变量吗?

时间:2013-11-14 18:22:47

标签: javascript anonymous-function userscripts

我正在寻找用usercript修改javascript游戏。

问题是所有游戏代码都包含一个像这样的匿名函数

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

我可以使用我的用户脚本访问JS变量吗?

编辑:

另请参阅:How to alter this javascript with Greasemonkey?

这个问题与Is it possible to gain access to the closure of a function?不一样!

2 个答案:

答案 0 :(得分:1)

不,您无法访问私有范围内的变量。

答案 1 :(得分:1)

是的! You can if you use the right browser (Firefox)

在用户脚本中(在Firefox上),您可以重写页面的JS以便自己访问。另见"How to alter this javascript with Greasemonkey?"

你的函数调用就像(对于内联脚本):

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);
}

然后您将访问变量,如:

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

唉,在 Chrome 用户脚本或Tampermonkey脚本中,仍然没有好办法做这种事情。

IF 有问题的JS的脚本是外部,然后是in Chrome, you can use beforeload to block it。然后注入您自己的代码 - 修改后公开该私有变量。

相关问题