【问题标题】:How to pass a variable value between background scripts in chrome extensions如何在 chrome 扩展中的后台脚本之间传递变量值
【发布时间】:2014-01-09 05:28:05
【问题描述】:

我正在开发一个谷歌浏览器扩展。我在我的一个后台 javascript 文件(example.js)中为变量设置了一个值。我需要访问或将此值传递给另一个背景 javascript 文件(extjs.js)。我该怎么做?有全局变量的概念吗?我的浏览器控制台没有出现任何错误。

我的清单.json

{
"name": "Example",
"version": "31.0.1650.57",
"manifest_version": 2,
"background":{
"scripts":["common.js","example.js","extjs.js"]
},
"content_scripts": [
{
"matches": ["<all_urls>"],
"js": ["myscript.js"]
}
]
}

我的例子.js

function trial()
{
/... some functionality../
var result = data;
}

我的 extjs.js

alert(result);

我知道我错过了一些东西。

问候, 尼基尔

【问题讨论】:

    标签: google-chrome-extension


    【解决方案1】:

    所有后台脚本共享相同的 JS 上下文,因此在其中一个脚本中声明的任何变量/函数都可供所有其他脚本使用(加载顺序当然会起作用)。

    当指定一个或多个后台脚本时,Chrome 会自动创建一个最小的 HTML 页面并在正文中插入一些 &lt;script&gt; 标签。例如。您自动生成的背景页面应如下所示:

    <html>
        <head></head>
        <body>
            <script src="common.js"></script>
            <script src="example.js"></script>
            <script src="extjs.js"></script>
        </body>
    </html>
    

    您可以通过导航至chrome://extensions 并选中Developer mode 复选框来查看您的背景页面。然后,在每个扩展程序下都有一个标记为“背景页面”的链接,您可以单击该链接打开背景页面的 DevTools 控制台。


    更新:

    我只是注意到您正试图从全局上下文(这是不可能的)访问一个函数局部变量(在 trial() 函数中定义)。

    由于var result 是在trial() 函数内定义的,因此在函数范围之外不可访问。 (即,您也无法从 example.js 引用它。)

    您需要像这样更改代码:

    example.js:

    var outer_result = 0;
    function trial() {
        var inner_result = 1;   // <-- this is a local variable
        outer_result = 2;       // <-- this is a global variable
    }
    // `inner_result` is undefined outside the function
    

    extjs.js:

    console.log(outer_result);   // <-- '0' since `trial()` is not invoked yet
    console.log(inner_result);   // <-- 'undefined' since it is never defined
    
    trial();   // <-- executing `trial()` function
    
    console.log(inner_result);   // <-- 'undefined' since it is function-local
    console.log(outer_result);   // <-- '2' since `trial()` modified it
    

    【讨论】:

    • 您不能同时使用background:scriptsbackground_page(也不需要)。您问题中发布的清单非常好,您应该能够从extjs.js(在前者之后加载)访问example.js 中定义的所有功能。在我的回答中,我确实建议改用 HTML background_page;我只是指出 Chrome 会自动为您生成一个(包括您指定的脚本)。好吧,我刚刚注意到您正在尝试从全局范围访问函数局部变量;我会更新我的答案。
    • @nikhil:如果你真的很喜欢这个答案,也请随意投票;)
    猜你喜欢
    • 2018-08-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多