My background script has a loop that keeps requesting data from an API I'm try to send messages from a background script to a content script but the message does not arrive.
I get the following error:
Unchecked runtime.lastError: Could not establish connection. Receiving end does not exist.
background.js
setInterval(async () => {
try {
//get some data in an API
//send the resuturn content to send message
var port = chrome.runtime.connect({ name: "knockknock" });
port.postMessage({ joke: "Knock knock" });
port.onMessage.addListener(function (msg) {
if (msg.question === "Who's there?")
port.postMessage({ answer: "Madame" });
else if (msg.question === "Madame who?")
port.postMessage({ answer: "Madame... Bovary" });
});
}
catch (e) {
console.error(e);
}
}, 10000);
content.js
chrome.runtime.onConnect.addListener(function (port) {
console.assert(port.name === "knockknock");
port.onMessage.addListener(function (msg) {
if (msg.joke === "Knock knock")
port.postMessage({ question: "Who's there?" });
else if (msg.answer === "Madame")
port.postMessage({ question: "Madame who?" });
else if (msg.answer === "Madame... Bovary")
port.postMessage({ question: "I don't get it." });
});
});