zurfyx
zurfyx

Reputation: 32767

Chrome Extension onMessage.addListener in background.js not being called

I want to be able to communicate from content-script (any tab) to background.

According to the documentation, I should be using chrome.extension chrome.runtime.onMessage with chrome.runtime.sendMessage.

So that's what I did:

manifest.json

"background": {
  "scripts": ["background.js"],
  "persistent": false
},
"permissions": [
  "*://*/*"
],

background.js

console.info('1');
chrome.runtime.onMessage.addListener((request, sender, sendReponse) => {
  console.info('2');
  sendReponse({ msg: 'foo' });
  return true;
});

I'm not very sure the return true; is needed. I tried with and without.

After building and reloading the extension I accessed chrome background page through chrome://extensions

> 1 // background.js file was run
> chrome.runtime.sendMessage({ hello: 'so' }, v => console.info(v))
> undefined
> undefined // This is the callback response I get. Why?

More important, I also get an empty response callback when running sendMessage from other tabs (i.e. stackoverflow.com)

> chrome.runtime.sendMessage('extension id', { hello: 'so' }, v => console.info(v))
> undefined
> undefined

Why do I get an empty response callback?

Am I missing any special permission? Wrong parameters? Maybe wrong API functions to do so?

Upvotes: 1

Views: 2740

Answers (1)

woxxom
woxxom

Reputation: 73616

  1. runtime.sendMessage doesn't send the message to the sender's context since Chrome 49.

    If sending to your extension, the runtime.onMessage event will be fired in every frame of your extension (except for the sender's frame),

  2. webpages can send messages to your background/event page in two cases:

    • externally_connectable key in manifest.json allowed that page
    • a content script of your extension is loaded for that page, in which case you can switch the context to your extension in the console toolbar to be able to send messages manually from console:

      pic

      The content script can be declared in manifest.json in which case it's autoinjected by [re]loading the page. Or you can inject it explicitly with tabs.executeScript from the background/event page.

Upvotes: 3

Related Questions