【问题标题】:Notification not shown in Chrome extension using Mozilla's webextension-polyfill使用 Mozilla 的 webextension-polyfill 的 Chrome 扩展中未显示通知
【发布时间】:2018-05-25 20:21:31
【问题描述】:

我刚开始开发一个 Firefox 插件。它在 Firefox 中运行良好,所以我想让它与 Coogle Chrome 扩展“兼容”。

为此,我注入了 Mozilla webextension-polyfill,基本上这个插件也在 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 中的方法。

这里是相关代码sn-ps...

ma​​nifest.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});
    });

【问题讨论】:

    标签: google-chrome-extension firefox-addon-webextensions polyfills webextension-polyfill


    【解决方案1】:

    这里有两个问题……

    问题 1

    onMessage 处理程序需要 return true。只有这样,polyfill 似乎才能正确处理消息。

    问题 2

    这看起来像是 polyfill 中的一个错误。在 Chrome 中,iconUrl 选项在创建通知时是必需,而在 Firefox 中它是可选

    如果我应用这两件事,通知在 Firefox 和 Chrome 中有效。

    【讨论】:

      猜你喜欢
      • 2014-09-17
      • 1970-01-01
      • 1970-01-01
      • 2015-04-10
      • 2023-02-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-06-26
      相关资源
      最近更新 更多