ReferenceError:浏览器未定义
无法通过控制台在页面上找到WebExtension API。 在后台脚本中,所有API工作正常。
https://developer.mozilla.org/en-US/Add-ons/WebExtensions/Content_scripts#WebExtension_APIs
如何通过WebExtension API发送/接收消息(第51页)。
答案 0 :(得分:3)
以下是单击按钮时打印通知的示例(适用于我)。
不要忘记在清单中声明您的需求权限。
免责声明:似乎Firefox为浏览器变量抛出错误,但它确实有效。
{
"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"
]
}
<!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>
window.addEventListener("click", notifyExtension)
function notifyExtension(e) {
if (e.target.id !== 'pony') {
return
}
browser.runtime.sendMessage('FooBar')
}
browser.runtime.onMessage.addListener(notify)
function notify(message) {
browser.notifications.create({
"type": "basic",
"title": "You clicked a link!",
"message": message
})
}