I'm writing a chrome extension, but can't send messages from the background script to the content script. I keep getting the error Could not establish connection. Receiving end does not exist.
I have read the chrome.runtime and chrome.tabs docs, but it doesn't work as expected.
This is my manifest file:
{
"name": "chrome extension",
"version": "1.0.0",
"description": "Extension",
"icons": {
"16": "images/16.png",
"32": "images/32.png",
"48": "images/48.png",
"128": "images/96.png"
},
"manifest_version": 3,
"author": "",
"background": {
"service_worker": "background.js",
"type": "module"
},
"permissions":[
"bookmarks",
"storage",
"tabs",
"activeTab"
],
"action":{
"default_popup": "index.html",
"default_title": "Extension"
},
"commands": {
"switch-to-folder-1": {
"suggested_key": "Ctrl+Shift+1",
"description": "Switch folder 1"
}
}
}
This method is written in the background script:
chrome.commands.onCommand.addListener(async (command) => {
const [tab] = await chrome.tabs.query({active: true, currentWindow: true})
const response = await chrome.tabs.sendMessage(tab.id, {greeting: "hello"});
console.log(response);
});
and this one in the content script (which is included programmaticaly, not via the manifest file):
chrome.runtime.onMessage.addListener(function (request, sender, sendResponse) {
console.log(
sender.tab
? 'from a content script:' + sender.tab.url
: 'from the extension'
);
if (request.greeting === 'hello') sendResponse({ farewell: 'goodbye' });
});
So I expect that when I press Ctrl+Shift+1, that the command fires, which does work. Then it should send a message to the content script and log the response to the console which should be { farewell: 'goodbye' }.
What I get instead is an Uncaught (in promise) error: Could not establish connection. Receiving end does not exist. Regardless of which tab I am on, how many times I reload the extension... always this error.