My chrome extension has the following two javascripts:
background.js
, running as background script:
chrome.runtime.onMessage.addListener(function(message, sender, sendResponse) {
if (message.data == "takeScreenshot") {
var resp = sendResponse;
chrome.tabs.captureVisibleTab(function(screenshotUrl) {
resp({
screenshot: screenshotUrl
});
});
return true; // Return true to tell that the response is sent asynchronously
} else {
return "TestReply";
}
});
api.js
, running as web accessible resource:
window.takeScreenshot = (function() {
var isTakingScreenshot = false; // Semaphore
return function() {
if(isTakingScreenshot) return Promise.reject();
isTakingScreenshot = true;
return new Promise(function(resolve, reject) {
chrome.runtime.sendMessage("eomfljlchjpefnempfimgminjnegpjod", "takeScreenshot", function(response) {
console.log(response);
isTakingScreenshot = false;
resolve(response.screenshot);
});
});
}
})()
window.test = (function() {
return function() {
return new Promise(function(resolve, reject) {
chrome.runtime.sendMessage("eomfljlchjpefnempfimgminjnegpjod", "test", function(response) {
console.log(response);
resolve(response.length);
});
});
}
})();
When I execute in a tab's console either function (auto-complete knows them, so they are available), I get the error:
Unchecked runtime.lastError: Could not establish connection. Receiving end does not exist.
and the respone returned is undefined.
I have checked that the id in sendMessage
is the same as in the manifest and in the chrome://extensions page, and I have opened the background page DevTools of the extension and manually added the same listener there to make sure the listener is indeed registered.
My searches found that this error means the listener has not been correctly registered, but I don't find the underlying reason. Do you have an idea what causes this error?
externally_connectable
is different from generalpermissions
? It seemed like I was able to usechrome.runtime.sendMessage()
andchrome.runtime.onMessage.addListener()
without any problems for years without understanding theexternally_connectable
setting.