I want to send a message from a content script injected in a web page to the background of the Chrome extension, but getting the famous chrome.runtime.lastError
with error message 'Could not establish connection. Receiving end does not exist.'
I have the next manifest.json
{
"manifest_version": 2,
"name": "Sample Name",
"version": "1.0.0",
"description": "Sample description",
"short_name": "Short Sample Name",
"permissions": ["tabs", "https://google.com/*", "activeTab", "declarativeContent", "storage"],
"externally_connectable": {
"ids": ["{my_extension_id}"],
"matches": ["https://www.google.com/*"]
},
"content_scripts": [
{
"ids": ["{my_extension_id}"],
"matches": ["https://www.google.com/*"],
"js": [
"content.js"
],
"css": ["test.css"]
}
],
"browser_action": {
"default_title": "Sample title",
"default_popup": "popup.html",
"default_icon": {
"16": "icons/icon16.png",
"32": "icons/icon32.png"
}
}
}
the next content.js
const extensionId = "{my_extension_id}";
const url = window.location.href;
function ping() {
chrome.runtime.sendMessage(extensionId, "ping", (response) => {
if (chrome.runtime.lastError) {
console.log("chrome.runtime.lastError again...");
setTimeout(ping, 1000);
} else {
chrome.runtime.sendMessage(
extensionId,
{ url: url },
function (response) {
console.log(response);
}
);
}
});
}
ping();
and the next background.js
chrome.app.runtime.onLaunched.addListener(function () {
chrome.app.window.create("window.html", {
outerBounds: {
width: 500,
height: 500,
},
});
});
chrome.runtime.onConnect.addListener((port) => {
console.log("connected ", port);
port.onMessageExternal.addListener(function (request, sender, sendResponse) {
if (blocklistedWebsite.includes(sender.url)) return;
sendResponse({
success: true,
msg: "I have received your message",
});
});
});
const blocklistedWebsite = [];
chrome.runtime.onMessageExternal.addListener(function (request, sender, sendResponse) {
sendResponse({
success: true,
msg: "I have received your message",
});
});
I tried to do it correct, but now I'm getting a message about chrome.runtime.lastError
every second in the web page console. I use the latest version of Chrome.