Google chrome extension 使用Mozilla';s webextension polyfill
我刚开始开发Firefox插件。它在Firefox中运行良好,因此我想让它与Coogle Chrome扩展“兼容” 为此,我注入了Mozilla,基本上该插件也在Chrome中运行。但是有一件事我不能去工作 在Firefox中,如果内容脚本发送后台脚本接收到的消息,则会向用户显示通知。在Chrome中运行此命令会导致以下异常:Google chrome extension 使用Mozilla';s webextension polyfill,google-chrome-extension,firefox-addon-webextensions,polyfills,webextension-polyfill,Google Chrome Extension,Firefox Addon Webextensions,Polyfills,Webextension Polyfill,我刚开始开发Firefox插件。它在Firefox中运行良好,因此我想让它与Coogle Chrome扩展“兼容” 为此,我注入了Mozilla,基本上该插件也在Chrome中运行。但是有一件事我不能去工作 在Firefox中,如果内容脚本发送后台脚本接收到的消息,则会向用户显示通知。在Chrome中运行此命令会导致以下异常: Uncaught (in promise) {message: "The message port closed before a response was recei
Uncaught (in promise)
{message: "The message port closed before a response was received."}
callbackArgs @ VM18 browser-polyfill.js:630
sendResponseAndClearCallback @ VM29 extensions::messaging:417
disconnectListener @ VM29 extensions::messaging:441
EventImpl.dispatchToListener @ VM19 extensions::event_bindings:403
publicClassPrototype.(anonymous function) @ VM25 extensions::utils:138
EventImpl.dispatch_ @ VM19 extensions::event_bindings:387
EventImpl.dispatch @ VM19 extensions::event_bindings:409
publicClassPrototype.(anonymous function) @ VM25 extensions::utils:138
dispatchOnDisconnect @ VM29 extensions::messaging:378
我可以看出这来自于webextension polyfill
,但我找不到一种方法使通知也显示在Chrome中
以下是相关的代码片段
manifest.json
{
"manifest_version": 2,
// ...
"background": {
"scripts": [
"lib/browser-polyfill.js",
"background-script.js"
],
"persistent": false
},
"options_ui": {
"page": "settings/options.html"
}
}
后台脚本.js
function notify(message) {
if (message.copied) {
browser.notifications.create({
"type": "basic",
"title": "Notifaction title",
"message": "Hello, world!"
});
}
}
browser.browserAction.onClicked.addListener(() => {
browser.tabs.executeScript({file: "lib/browser-polyfill.js"});
browser.tabs.executeScript({file: "content-script.js"});
});
browser.runtime.onMessage.addListener(notify);
browser.storage.local.get({elementId: ""})
.then(() => {
browser.runtime.sendMessage({copied: true});
});
content script.js
function notify(message) {
if (message.copied) {
browser.notifications.create({
"type": "basic",
"title": "Notifaction title",
"message": "Hello, world!"
});
}
}
browser.browserAction.onClicked.addListener(() => {
browser.tabs.executeScript({file: "lib/browser-polyfill.js"});
browser.tabs.executeScript({file: "content-script.js"});
});
browser.runtime.onMessage.addListener(notify);
browser.storage.local.get({elementId: ""})
.then(() => {
browser.runtime.sendMessage({copied: true});
});
这里有两个问题 问题1
onMessage
处理程序需要一个返回true
。只有这样,polyfill才能正确处理消息
问题2
这看起来像是polyfill中的一个bug。在Chrome中,创建通知时需要使用iconUrl
选项,而在Firefox中则是可选的
如果我应用这两件事,那么通知在Firefox和Chrome中都会起作用