I am trying to pass a url on the current tab from contentScript to background and display it in console. But I am alaways getting one error :
Uncaught (in promise) Error: Could not establish connection. Receiving end does not exist.
Here is my manifest.json:
{
"manifest_version": 3,
"name": "My Extension",
"version": "1.0",
"content_scripts": [
{
"matches": ["<all_urls>"],
"js": ["contentScript.js"]
}
],
"permissions": ["scripting", "activeTab"],
"background": {
"service_worker": "background.js"
}
}
Here is my contentScript.js
// contentScript.js
chrome.runtime.onMessage.addListener(function (message, sender, sendResponse) {
if (message.type === "executeScript") {
var script = new Script(message.script);
document.head.appendChild(script);
}
});
chrome.runtime.sendMessage({
type: "printToConsole",
message: "Hello from the content script!",
});
function getActiveTab() {
chrome.runtime.sendMessage({ type: "getActiveTabRequest" });
}
chrome.runtime.onMessage.addListener(function (message, sender, sendResponse) {
if (message.type === "getActiveTabRequest") {
const activeTab = message.activeTab;
console.log("Active tab URL:", activeTab.url);
}
});
getActiveTab();
Here is my background.js
// background.js
chrome.runtime.onMessage.addListener(function (message, sender, sendResponse) {
if (message.type === "executeScript") {
var script = new Script(message.script);
chrome.scripting.executeScript({
target: { tabId: sender.tab.id },
func: script,
});
}
});
chrome.runtime.onMessage.addListener(function (message, sender, sendResponse) {
if (message.type === "printToConsole") {
console.log(message.message);
}
});
chrome.runtime.onMessage.addListener(function (message, sender, sendResponse) {
if (message.type === "sendData") {
const data = message.data;
console.log("Received data from content script:", data);
// Process the data here
}
});
chrome.runtime.onMessage.addListener(function (message, sender, sendResponse) {
if (message.type === "getActiveTabRequest") {
(async () => {
const tabs = await chrome.tabs.query({
active: true,
currentWindow: true,
});
const activeTab = tabs[0];
chrome.runtime.sendMessage({
type: "getActiveTabRequest",
activeTab: activeTab,
});
})();
}
});
What am I doing wrong? Much appreciated!!