Firefox WebExtension API "browser is not defined"

Firefox WebExtension APIs "browser is not defined"

ReferenceError: 浏览器未定义

无法通过控制台在页面上找到 WebExtension API。 在后台脚本中,所有 API 都工作正常。

https://developer.mozilla.org/en-US/Add-ons/WebExtensions/Content_scripts#WebExtension_APIs

如何通过页面上的 WebExtension API send/receive 消息 (Firefox 51)。

这是一个在您单击按钮时打印通知的示例(对我有用)。

不要忘记在清单中声明您需要的权限。

免责声明:似乎 Firefox 为浏览器变量抛出错误,但它有效。


manifest.json

{
    "manifest_version": 2,
    "name": "webextension-example",
    "version": "0.1",
    "description": "An example.",
    "background": {
        "scripts": ["background.js"]
    },
    "content_scripts": [
        {
            "matches": ["<all_urls>"],
            "js": ["script.js"]
        }
    ],
    "permissions": [
        "notifications",
        "activeTab"
    ]
}

index.html

<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="content-type" content="text/html; charset=utf-8" />
    </head>
    <body>
        <button id="pony">Notify</button>
        <script src="script.js"></script>
    </body>
</html>

script.js

window.addEventListener("click", notifyExtension)
function notifyExtension(e) {
    if (e.target.id !== 'pony') {
        return
    }
    browser.runtime.sendMessage('FooBar')
}

background.js

browser.runtime.onMessage.addListener(notify)
function notify(message) {
    browser.notifications.create({
        "type": "basic",
        "title": "You clicked a link!",
        "message": message
    })
}