I am developing a chrome extension that needs to send message from extension background page to content script but I keep getting the following error no matter what I do: "Unchecked runtime.lastError: Could not establish connection. Receiving end does not exist."
The message that the background script is sending, is being fetched by an API which runs on every url change.
Here is the manifest.json file:
{
"manifest_version": 2,
"name": "tool",
"description": "help tool",
"version": "1.0",
"icons": {
"16": "icons/icon16.png",
"32": "icons/icon32.png",
"48": "icons/icon48.png",
"128": "icons/icon128.png"
},
"page_action": {
"default_icon": "icons/icon128.png",
"default_popup": "src/popup.html",
"default_title": "tool"
},
"background": {
"scripts": [
"src/background.js"
],
"persistent": true
},
"web_accessible_resources": [
"src/content.css"
],
"content_scripts": [
{
"matches": [
"https://*"
],
"js": [
"src/jquery-3.4.1.min.js",
"src/content.js"
],
"css": [
"src/content.css"
]
}
],
"permissions": [
"tabs",
"Api URL"
]
}
Here is the code which I am using in the background and content script:
background.js- callApi is being called on every url change through chrome.tabs.onUpdated.addListener function:
chrome.tabs.onUpdated.addListener(() => {
chrome.tabs.query({active: true, currentWindow: true},function(tabs) {
var tab = tabs[0];
var url = tab.url;
var para = "url=" + url
console.log(para)
callApi(para)
})
})
const callApi = (para) => {
var url = "API URL" + para
fetch(url)
.then((response) => {
return response.text();
})
.then((data) => {
console.log(data);
connectToCurrentTab(data);
})
}
function getCurrentTabId(cb) {
var query = {active: true, currentWindow: true};
chrome.tabs.query(query, function(tabArray) {
cb(tabArray[0].id)
});
}
function connectToCurrentTab (data) {
getCurrentTabId(function(currentTabId) {
var port = chrome.tabs.connect(currentTabId, {name: "knock"})
port.postMessage(data);
port.onMessage.addListener((msg) => {
return true;
});
});
}
content.js:
chrome.runtime.onConnect.addListener(port => {
console.log('connected ', port);
if (port.name === 'knock') {
port.onMessage.addListener(function(msg) {
var data = JSON.parse(msg)
port.postMessage({data: "received"});
});
}
});
I am able to get the data in the content script but it is also showing the error. Can anyone help me to solve this? Any help is greatly appreciated.
https://URLs per your manifest.json. 2) chrome.tabs.onUpdated is invoked on all tabs, not just the active ones, so your code should be fixed, see the documentation and use the parameters accordingly. - wOxxOm