【问题标题】:Chrome extension global variableChrome 扩展全局变量
【发布时间】:2018-03-27 17:21:06
【问题描述】:

我查看了关于带有清单版本 2 的 Chrome 扩展程序的其他全局变量问题,但一无所获。

假设我有 2 个文件:

// content.js

var myVariable = myVariable(someDiv);
var myVarWithGlobe = VarWithGlobe.fromVariable(myVariable);

// VarWithGlobe.js

var withGlobe = withGlobe || { };

withGlobe.WithGlobe = (function(global) {
    var myLocalVar = global.myVariable;
....

WithGlobe.fromVariable = WithGlobe;

它们都被添加到 web_accessible_resources, content_scripts 但我无法访问第二个文件中的 global.myVariable,因为它是未定义的。

如果不允许我更改 VarWithGlobe.js,我该如何获取它?

【问题讨论】:

    标签: javascript google-chrome google-chrome-extension


    【解决方案1】:

    内容脚本有自己的执行上下文(它甚至与它们正在执行的网页上下文不同)。唯一的方法是使用变量将消息传递到/从背景页面传递。查看this answer 获取代码示例

    【讨论】:

      【解决方案2】:

      在 Chromium 版本 35.0.1916.114 以及可能在所有最新的 Chrome 版本中,当您在 Chrome 控制台上进行测试时,可以存储全局变量。

      例如,如果您在代码中使用 console.log() 作为变量,当您在浏览器控制台上看到它时,您可以通过右键单击它来存储它 并选择“存储为全局变量”

      希望对你有帮助!

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-03-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-10-25
        • 2017-08-15
        相关资源
        最近更新 更多