I am trying to send a message from my background script to my content script. Every time I load the extension, I immediately get these two errors in the Service Worker:
Unchecked runtime.lastError: Could not establish connection. Receiving end does not exist.
followed by
Error handling response: TypeError: Cannot read properties of undefined (reading 'farewell')
at chrome-extension://kglmnphkfjhfplfdmjfhegdedeochkmc/background.js:3:28
Here is my code, copied from these Google Chrome Extension developer guides:
https://developer.chrome.com/docs/extensions/mv3/getstarted/
https://developer.chrome.com/docs/extensions/mv3/messaging/
manifest.json
{
"name": "Getting Started Example",
"description": "Build an Extension!",
"version": "1.0",
"manifest_version": 3,
"background": {
"service_worker": "background.js"
},
"permissions": ["storage"],
"content_scripts": [
{
"matches": ["<all_urls>"],
"run_at" : "document_end",
"js" : ["contentscript.js"]
}
]
}
background.js
chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
chrome.tabs.sendMessage(tabs[0].id, {greeting: "hello"}, function(response) {
console.log(response.farewell);
});
});
contentscript.js
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"});
}
);
I have tried disabling all of my other Chrome extensions and the problem persists.