我刚开始开发Firefox插件。它在Firefox中运行得很好,所以我想让它与Coogle Chrome扩展“兼容”。
为此,我注入Mozilla 网页扩展-多层填充,基本上插件也运行在Chrome中。但有一件事我不能去工作..。
在Firefox中,如果内容脚本发送由后台脚本接收的消息,就会向用户显示一个通知。在Chrome中运行这个程序会导致以下异常:
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"
}
}background-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);content-script.js
browser.storage.local.get({elementId: ""})
.then(() => {
browser.runtime.sendMessage({copied: true});
});发布于 2018-05-25 21:36:05
这里有两个问题。
问题1
onMessage处理程序需要一个return true。只有这样,多填充才能正确地处理消息。
问题2
这看上去像是多数派中的一个bug。在Chrome中,创建通知时需要使用iconUrl选项,而在火狐中则是可选的。
如果我应用这两种方法,通知可以在Firefox和Chrome中使用。
https://stackoverflow.com/questions/50536349
复制相似问题