从浏览器控制台访问 Greasemonkey/Tampermonkey 变量?

Łuk*_*ąsa 5 javascript greasemonkey tampermonkey browser-console

这是来自用户脚本的代码示例:

var ExampleObj = {
  somevar1:'value1',
  somevar2:'value2',
  somevar3:'value3',
  somefunction1:function(){
    //do sth
  },
  somefunction2:function(){
    //do sth else
  }
}
Run Code Online (Sandbox Code Playgroud)

当我尝试从脚本调用我的函数时:一切正常,但我无法从浏览器控制台访问:

(参考错误:未定义 ExampleObj)


我的 Greasemonkey/Tampermonkey 设置(元数据):

// ==UserScript==
// @name     [this is my secret]
// @version  1
// @run-at document-end
// @include [this is my secret]
// @grant    none
// ==/UserScript==
Run Code Online (Sandbox Code Playgroud)

脚本有效;我只需要从浏览器控制台访问这些功能。

Bro*_*ams 6

@grant none模式下,脚本仍然在受保护的范围内运行。通过更改以下内容将对象置于全局范围内:

var ExampleObj = {
Run Code Online (Sandbox Code Playgroud)

到:

window.ExampleObj = {
Run Code Online (Sandbox Code Playgroud)

然后您将能够看到并使用该对象。(注意目标网页也可以看到并使用它。)

请参阅“访问从 Greasemonkey 到 Page 的变量,反之亦然”以获取更多信息以及@grant非 none 时的场景。