问题描述
ReferenceError:未定义浏览器
ReferenceError: browser is not defined
无法通过控制台在页面上找到WebExtension API.在后台脚本中,所有API都可以正常工作.
Cannot find WebExtension APIs on page via console.In background script all APIs working fine.
https://developer.mozilla.org/en -US/附加组件/WebExtensions/Content_scripts#WebExtension_APIs
如何通过网页(Firefox 51)上的WebExtension API发送/接收消息.
How to send/receive message via WebExtension APIs on page (Firefox 51).
推荐答案
下面是一个示例,当您单击按钮时,它会打印通知(对我有用).
Here is an example that print a notification when you click on the button (it works for me).
不要忘记在清单中声明您所需的权限.
Do not forget to declare the permissions for your needs in the manifest.
免责声明:Firefox似乎为浏览器变量抛出了一个错误,但它可以正常工作.
Disclaimer: it seems that Firefox throw an error for browser variable, but it works.
{
"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
})
}
这篇关于Firefox WebExtension API“未定义浏览器".的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!