I am updating my chrome extension from Manifest 2 to Manifest 3. In refactoring my code I wanted to add message passing from the background.js to content.js. When I do that I get the error: "Unchecked runtime.lastError: Could not establish connection. Receiving end does not exist."
manifest.json
{
"name": "project-name",
"version": "1.0.0",
"manifest_version": 3,
"description": "description",
"permissions": [
"activeTab",
"alarms",
"declarativeContent",
"storage",
"tabs",
],
"background": {
"service_worker": "background.js"
},
"content_scripts": [
{
"matches": [
"*://*.myurl.nl/*",
],
"js": ["content.js"],
"run_at": "document_start"
}
],
"action": {
"default_popup": "views/popup/popup.html",
"default_icon": {
"16": "images/icon16.png",
"32": "images/icon32.png",
"48": "images/icon48.png",
"128": "images/icon128.png"
}
},
"icons": {
"16": "images/icon16.png",
"32": "images/icon32.png",
"48": "images/icon48.png",
"128": "images/icon128.png"
}
}
background.js
chrome.runtime.onInstalled.addListener(() => {
chrome.storage.local.get('state', (data) => {
if (data.state === false) {
chrome.storage.local.set({state: false});
} else {
chrome.storage.local.set({state: true});
}
});
const startAlarm = async (name, duration) => {
chrome.alarms.create(name, { delayInMinutes: duration });
};
startAlarm()
chrome.declarativeContent.onPageChanged.removeRules(undefined, () => {
chrome.declarativeContent.onPageChanged.addRules([
{
conditions: [
new chrome.declarativeContent.PageStateMatcher({
pageUrl: {
urlContains: 'myurl.'
}
})
],
actions: [new chrome.declarativeContent.ShowAction()]
}
]);
});
});
chrome.alarms.onAlarm.addListener((alarm) => {
if (alarm.name === 'extension') {
chrome.storage.local.get(['state'], async (data) => {
if (data.state !== true) {
chrome.alarms.clear('extension');
return;
}
const [tab] = await chrome.tabs.query({ active: true, lastFocusedWindow: true });
if (tab.id) {
const res = await chrome.tabs.sendMessage(tab.id, { name: 'my-message' });
console.log(res);
} else {
console.error('error');
}
});
}
});
content.js
console.log('Reached content script file'); // this is reached
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
console.log('Reached addListener'); // never reached
if (message.name === 'my-message') {
handleAction();
}
return true;
});
const handleAction = () => {
....some code that is never reached
}
popup.js
console.log('Reached') // never reached
function addButton() {
...code that is never reached
}
chrome.storage.local.get('state', (data) => {
addButton(data.state === true);
});
I have read other people online have the same issue. I have tried removing my extension and reloading it, no luck. What may I doing wrong resulting in the above error/why am I unable to send my message and listen to it. Appreciate any insight.
Thanks in advance. (I have slightly adjusted code for privacy reasons i.e. myurl will be something else)