Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Chrome Runtime OnMessage Listener event not firing

script/contentscript.js

'use strict';

chrome.runtime.onMessage.addListener(function(message, sender, sendResponse){
     alert("hi");
     return true;
});

chrome.runtime.sendMessage(null, {hello:"hello"});

I'm at a loss. Either addListener isn't registering the callback, the callback isn't being fired when a message is sent, or something in between. I've done what I can to limit the possible errors. At one point the sendMessage was in my popup.js and after hours of trying different variations, I ported it to another computer. When I got desperate enough to put the sendMessage in the same file it was a surprise to find sendMessage wouldn't work even in the same contentscript!

I've used both runtime and tabs objects as well as every variation of both sendMessage and onMessage.addListener.

One odd thing is that when on a breakpoint in the content script, I've seen hasListener usually return false and hasListeners return true after my listener is added.

{
  "name": "__MSG_appName__",
  "version": "0.0.1",
  "manifest_version": 2,
  "description": "__MSG_appDescription__",
  "icons": {
  "16": "images/icon-16.png",
  "128": "images/icon-128.png"
},
  "default_locale": "en",
  "content_scripts":[
{
   "matches": ["http://*/*", "https://*/*"],
   "js":["scripts/contentscript.js"]
}
],
   "browser_action": {
   "default_icon": {
   "19": "images/icon-19.png",
   "38": "images/icon-38.png"
 },
   "default_title": "pluralsight dl",
   "default_popup": "popup.html"
},
   "options_page": "options.html",
   "permissions":[
   "activeTab",
   "tabs",
   "http://*/*",
   "https://*/*"
]
}

Any ideas on why this wouldn't work? Both computers are using Version 43.

A popup js message that also doesn't register. Same extension package.

script\popup.js

'use strict';

console.log('\'Allo \'Allo! Popup');
// File executed, it's ready for the message
chrome.runtime.sendMessage(null, { action: "start"});
like image 548
user2397965 Avatar asked Oct 24 '25 06:10

user2397965


1 Answers

sendMessage never fires the event in the same context. Only other contexts receive the message.

As for your initial problem, there are 2 forms of sendMessage: runtime.sendMessage sends messages to extension's own pages (origin chrome-extension://yourId/) and tabs.sendMessage that sends messages to content scripts. See this question for more details.

like image 166
Xan Avatar answered Oct 26 '25 19:10

Xan