Notification not shown in Chrome extension using Mozilla's webextension-polyfill

620 views Asked by At

I just started with developing a Firefox add-on. It works fine in Firefox so I'd like to make it "compatible" to a Coogle Chrome extension.

For this I inject Mozilla webextension-polyfill and basically the add-on also runs in Chrome. There is one thing however I can't get to work...

In Firefox a notifcation is shown to the user if the content script sends a message which is received by the background script. Running this in Chrome results in the following exception:

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

I can tell that this comes from the webextension-polyfill but I cannot find a way so that the notification is also shown in Chrome.

Here are the relevant code snippets...

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});
    });
1

There are 1 answers

0
Robert Strauch On

There are two problems here...

Issue 1

The onMessage handler needs a return true. Only then the polyfill seems to be able to handle the messages correctly.

Issue 2

This seems to look like a bug in the polyfill. In Chrome the iconUrl option is required when creating a notification whereas it is optional in Firefox.

If I apply these two things the notification works in Firefox and Chrome.