简体   繁体   English

使用Greasemonkey访问Javascript私有变量

[英]Accessing Javascript private variables with Greasemonkey

function Foo1() {
    var bar = 'test';
}

AFAIK, it is impossible to access the variable bar from global scope, unless one writes a privileged function to do so, such as AFAIK,除了编写特权函数之外,不可能从全局范围访问变量条,例如

function Foo2() {
    var bar = 'test';
    this.read = function(){return bar;};
}

Does Greasemonkey (or any other tool) provide any means to access the variable bar, short of re-defining the entire function Foo1 with Foo2? Greasemonkey(或任何其他工具)是否提供了访问变量条的任何方法,而不是用Foo2重新定义整个函数Foo1? Greasemonkey has GM_xmlhttprequest which sidesteps certain restrictions, so I was wondering if it could do this too and save me some issues. Greasemonkey有GM_xmlhttprequest,它可以避免某些限制,所以我想知道它是否也可以做到这一点并为我节省一些问题。

What I am trying to do currently is to read and write a private variable embedded in a function, which is also itself located in a separate .js include. 我目前要做的是读取和编写嵌入在函数中的私有变量,该函数本身也位于单独的.js包含中。 Thus, I cannot directly modify the script, and I have to load the .js with AJAX, carry out the modification, and then overwrite the original script. 因此,我不能直接修改脚本,我必须用AJAX加载.js,进行修改,然后覆盖原始脚本。 This is very cumbersome and I would like an easier way to carry this task out. 这非常麻烦,我想要一个更简单的方法来完成这项任务。

GM_xmlhttprequest just bypasses browser security. GM_xmlhttprequest只是绕过浏览器安全性。 Variable scope, on the other hand, is part of the language and the Javascript VM. 另一方面,可变范围是语言和Javascript VM的一部分。 Short of modifying the Javascript VM, there is no way to access those 'private' variables outside the function scope. 如果没有修改Javascript VM,就无法访​​问函数范围之外的那些“私有”变量。

If Foo1 is not a native function and you do know the pattern of the function, then you can get the content of the variable by using: 如果Foo1不是本机函数并且您确实知道函数的模式,那么您可以使用以下方法获取变量的内容:

var bar = /bar = '(\w+)'/.test(Foo1.toString()) && RegExp.$1;
alert(bar); // will return "test"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM