To fix ‘Unchecked runtime.lastError: Could not establish connection. Receiving end does not exist.’ with JavaScript, we should make sure the background worker is ready to receive messages.
For instance, we write
chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {
chrome.tabs.sendMessage(tabs[0].id, { greeting: "hello" }, (response) => {
console.log(response);
});
});
in background.js to receive message with query
.
Then we add message listener in content.js with
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
console.log(request, sender, sendResponse);
sendResponse("received:", JSON.stringify(request));
});
We call addListener
to listen for messages and get the received message from request
.