在 WebExtension 的背景和内容脚本中调用 API 键

Calling API Keys in background and content scripts in WebExtension

我的扩展程序需要一个 API 密钥和密码,我已将它们存储在一个文件中,格式如下。

key.js

var APP_KEY = 'App Key Goes Here';
var APP_SEC = 'App Secret Goes Here';

manifest.json

// manifest.json
{
    "manifest_version": 2,
    "name": "Trakt for IMDb",
    "version": "0.1a",
    "background": {
        "scripts": [
                "js/key.js",
                "js/background.js"]
    },
    "content_scripts": [
        {
            "js": [
                "js/key.js",
                "js/main.js"
            ]
        }
    ]
}

在弹出页面上,我可以像 <script type="text/javascript" src="../js/key.js"></script> 一样引用这个文件,它调用 2 个变量,但我不知道如何引用它,所以我的背景和内容脚本也可以访问它们。

我试过在我的 manifest.json 文件中引用 key.js 文件,如下所示

"background": {
    "scripts": [
        "js/key.js",
        "js/background.js"
    ]
}

但这不起作用。我收到 APP_KEY is not defined

main.js

console.log('Content: ' + APP_KEY);

有什么方法可以尝试做我正在做的事情吗?

这会按照您想要的方式工作。单个 JavaScript 文件可用于后台脚本和内容脚本以共享相同的函数或变量。

background key run in the same context 中定义的所有脚本。因此,在 key.js 中定义的变量 APP_KEYAPP_SEC 可用于 background.js.

中的代码

在单个 js key within a manifest.json file's content_scripts key share a single context. This is what allows you to use things like jQuery with your code. I have not checked to see if there is a separate context created for separate js lists, if the matches key results in both sets being loaded on a particular page, or tab. In addition, I have not checked to see if a single context is shared between the manifest.json file's content_scripts method of loading content scripts and other methods of loading content scripts (e.g. tabs.executeScript‌​()).

中定义的所有脚本

以下是已在 Firefox 和 Google Chrome 中测试的完整扩展。在这两种浏览器中,key.js 中定义的变量在后台和内容脚本中都可用。

manifest.json:

{
    "manifest_version": 2,
    "name": "Variables in other files",
    "description": "Test availability of variables from anther JavaScript file",
    "version": "0.1",
    "background": {
        "scripts": [
                "js/key.js",
                "js/background.js"]
    },
    "content_scripts": [
        {
            "matches": ["*://*.mozilla.org/*"],
            "js": [
                "js/key.js",
                "js/contentScript.js"
            ]
        }
    ]
}

js/key.js:

var APP_KEY = 'App Key Goes Here';
var APP_SEC = 'App Secret Goes Here';

js/background.js:

console.log('Background: ' + APP_KEY);
console.log('Background: ' + APP_SEC);

js/contentScript.js:

console.log('Content: ' + APP_KEY);
console.log('Content: ' + APP_SEC);

加载扩展时的控制台输出:

Background: App Key Goes Here
Background: App Secret Goes Here

导航到 mozilla.org 时的控制台输出:

Content: App Key Goes Here
Content: App Secret Goes Here

我不确定为什么在您最初尝试时它对您不起作用。您在评论中表示它现在对您有效。