Hi,
I have an extension that has a background.js, which includes the Alarms and Tabs api.
I want to run a function when the content-script.js is injected and then run the function again at a set interval of every 10 seconds.
However, the chrome.tabs.sendMessage keeps showing a chrome.runtime.lastError of "Could not establish a connection. Receiving end does not exist."
Obviously, I'm doing something wrong here, I'm just not 100% sure of what it is.
Am I doing this right?
The relevant code looks like:
manifest.js
"permissions": ["alarms", "tabs"],
background.js
try {
chrome.alarms.create("myFunctionAlarm", { when: Date.now() + 10000 });
chrome.alarms.onAlarm.addListener(function (alarm) {
getCurrentTab().then((tab) => {
chrome.tabs.sendMessage(
tab.id, { name: 'myFunctionAlarm' }, function () {
if (!chrome.runtime.lastError) {
chrome.alarms.create("myFunctionAlarm", { when: Date.now() + 10000 });
}
});
});
}
});
} catch (error) {
console.error(error);
}
content-script.js
try {
myFunction();
chrome.runtime.onMessage.addListener(
function(request, sender, sendResponse) {
myFunction();
sendResponse();
{
}
);
} catch (error) {
console.log("Content-Script error:", error);
}