0

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"
    ],
engineer-x
  • 2,173
  • 2
  • 12
  • 25
  • 1
    This has to be the most often asked question with the "google-chrome-extension" tag :-) [Message passing > Simple one-time requests](https://developer.chrome.com/docs/extensions/mv3/messaging/#simple) "In the above example, sendResponse was called synchronously. If you want to asynchronously use sendResponse, add return true; to the onMessage event handler." – Thomas Mueller Oct 31 '22 at 07:49
  • Thanks! I had to include a single `return true;`. After reading the docs, I thought there needed to be a `return false;`, which is not correct. – engineer-x Nov 01 '22 at 04:59

0 Answers0