I have a sendMessage
sending "get_url" and expecting a response of the tab ID from the background script.
The expected response is the tab ID which I validated comes back at the console.log statement before the sendResponse()
.
But currently the result is undefined
from the console.log.
I read through https://developer.chrome.com/docs/extensions/mv3/messaging and found similar questions on this but nothing to address my issue.
There are no errors in the extension page.
content.js
chrome.runtime.sendMessage("get_url", (response) => {
console.log(response); // Expected tab ID; actual is undefined
});
background.js
async function getTabUrl() {
const [tab] = await chrome.tabs.query(
{ active: true, lastFocusedWindow: true });
return tab;
}
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
console.log("R: ", request);
if (request === "get_url") {
getTabUrl().then(tab => {
if (tab) {
console.log(tab.id); // Returns expected tab ID
sendResponse(tab.id);
}
});
}
});
manifest.json
{
"manifest_version": 3,
"name": "...",
"description": "Base Level Extension",
"version": "0.0.1",
"action": {
"default_popup": "popup.html",
"default_icon": "icons/favicon.ico"
},
"background": {
"service_worker": "background.js"
},
"content_scripts": [
{
"js": [
"scripts/content.js"
],
"matches": [
...
]
}
],
"permissions": [
"activeTab",
"tabs",
"storage"
],