'chrome.runtime.sendmessage not working in chrome extentions
hello I have a question I send to backgroud.js from content.js; but it is append error : Could not establish connection. Receiving end does not exist.
but it works fine that i think
content.js send chrome.runtime.sendMessage
background.js receive chrome.runtime.onMessage.addListener and menifest.json
chrome.runtime.sendMessage is it does not work
"background": { "service_worker": "background.bundle.js" },
"content_scripts": [
{
"matches": ["http://*/*", "https://*/*", "<all_urls>"],
"js": ["contentScript.bundle.js"],
"css": ["content.styles.css"]
}
],
background.js
chrome.runtime.onMessage.addListener(function (request, sender, sendResponse) {
switch (request.action) {
case "item-save": {
chrome.storage.local.get('item', function (itemData) {
let itemList = [];
if (Object.keys(itemData).length > 0) {
itemList = itemData.item;
}
itemList.push(request.source);
chrome.storage.local.set({
item: itemList
});
sendResponse("OK");
});
return true;
}
case "page-main": {
chrome.tabs.create({
url: chrome.runtime.getURL("options.html"),
});
return true;
}
default: return true;
}
});
content.js
button.addEventListener('click', () => {
chrome.runtime.sendMessage({
action : "item-save",
source : item
},function(response){
if(response ==="OK"){
let ok = confirm("check")
// if(ok){
// chrome.runtime.sendMessage({
// action : "page-main",
// });
// }
}
})
})
what's wrong?
Solution 1:[1]
It's a common chrome.runtime.onMessage bug that hopefully gets fixed one day.
I guess it gives an error when request.action is "page-main", since it's waiting for a sendResponse.
I think the solution would be to add an empty sendResponse() on "page-main".
You can also just use a return true; outside the switch and make it less redundant.:
chrome.runtime.onMessage.addListener(function (request, sender, sendResponse) {
switch (request.action) {
case "item-save": {
chrome.storage.local.get("item", function (itemData) {
// your code here ...
sendResponse("OK");
});
break;
}
case "page-main": {
chrome.tabs.create({
url: chrome.runtime.getURL("options.html"),
});
sendResponse(); // or try with sendResponse({})
break;
}
}
return true;
});
Also the chrome.storage functions are asynchronous.
So on "item-save" the sendResponse("OK"); will be executed before the chrome.storage.local.set.
If you want to run sendResponse after saving the itemList, it would be something like this:
chrome.storage.local.set({
item: itemList,
}, function () {
sendResponse("OK");
});
I hope it works! :)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Garu |
