I want to communicate between content.js and background.js, but it doesn’t work. There are no errors, and I can communicate between popup.js and background.js normally.
Here is my manifest.json:
{
"manifest_version": 3,
"name": "Test",
"version": "1.0",
"content_scripts": [
{
"matches": ["<all_urls>"],
"js": ["content.js"]
}
],
"background": {
"service_worker": "background.js"
},
"web_accessible_resources": [
{
"resources": ["sounds/test.mp3"],
"matches": ["<all_urls>"]
}
],
"permissions": [
"storage",
"activeTab",
"scripting",
"webNavigation",
"tabs"
],
"action": {
"default_popup": "popup.html",
"default_icon": {
"16": "icons/16.png",
"48": "icons/48.png",
"128": "icons/128.png"
}
}
}
Here is background.js:
console.log("BACKGROUND: Playing 60 second audio");
// This works and prints the code in extension console
chrome.runtime.sendMessage({ action: 'playAudio', data: "test.mp3"});
Here is content.js:
console.log("Loading content");
chrome.runtime.onMessage.addListener(function(message, sender, sendResponse) {
console.log("Message received in content script:", message);
if (message.action === 'playAudio') {
switch(message.data) {
case "test.mp3":
const test = new Audio(chrome.runtime.getURL('sounds/test.mp3'));
console.log("Playing test");
test.play();
break;
}}
});
The extension console prints the console.log, and the website console prints the first line when loading content.js, however, the communication between them doesn’t seem to be working. This works between popup.js, which I use for the popup itself, and background.js. The code is more or less the same there. What am I missing here?
I tried adding a lot of permissions. I tried changing from chrome.runtime to chrome.tabs, chrome.extension. I tried creating a new simple project with only the communication. I looked at other stackoverflow posts but none answer this question, at least for my specific case. I asked ChatGPT but everything it says doesn’t work.