Send message not working in onUpdated listener but does on browserAction.onClicked (background.js)

I’m trying to convert my Chrome extension into a Firefox addon, but ran into an issue with the addon not wanting to send messages from background to content script on the onUpdated listener, the weird thing is though, that it works on browserAction.onClicked.

Here’s the code, is this a bug, or just me doing something wrong? I don’t get it, spent most of yesterday trying to fix this, so hopefully will find out what the issue is today…

I tried making a whole new addon folder with only these 3 files, but I still get same error: Could not establish connection. Receiving end does not exist.

This means that the contentscript apparently isn’t listening, but why the hell does it work when I put the sendMessage inside the browserAction.onClicked and not the onUpdated? (both in background.js)

I’m running this in about:debugging, if that has anything to do with it btw…

manifest.json

{
"name": "Test addon",
"version": "1.0.0",
"manifest_version": 2,

"description": "Test",

"browser_action": {
    "default_title": "Test"
},

"background": {
"scripts":["background.js"]
},
"content_scripts": [
{
  "matches": ["http://*/*", "https://*/*"],
  "js": ["contentscript.js"]
}
],
"permissions": [
"cookies", "tabs", "http://*/*", "https://*/*"
]
}

background.js

browser.tabs.onUpdated.addListener(function(tabId, changeInfo, tabInfo){
if(changeInfo.status === "complete"){
    // This doesn't work, gives following error:
    // Error: Could not establish connection. Receiving end does not exist. - Shows in the browser console debug window (not console of window)
    browser.tabs.sendMessage(tabId, {action: "isInstalled"});
}
});

browser.browserAction.onClicked.addListener(function(tab) {
// This works
browser.tabs.sendMessage(tab.id, {action: "isInstalled"});
});

contentscript.js

browser.runtime.onMessage.addListener(function(request, sender) {
console.log("Message from the background script:");
if(request.action == "isInstalled"){
    alert("received");
}
});

Could it be that when you send the message from the background, the content script has not yet installed the message listener ?

You may want to try to tell your content script to load early. In the manifest.json:

"content_scripts": [
{
  "matches": ["http://*/*", "https://*/*"],
  "js": ["contentscript.js"],
  "run_at": "document_start"
}
1 Like

Hah, that actually did it. Thanks a lot man! :slight_smile: