0

No matter what I do, for some reason, I can't get my content script to communicate with my service worker, and get a response. I need this to obtain the tab id of my current tab, because it can't be obtained from content scripts.

I'm using chrome.runtime.sendMessage in my content script to send a message to the service worker, which is catching the message with chrome.runtime.onMessage.addListener, however, it doesn't receive the message, and I get an Uncaught TypeError: Cannot read properties of undefined (reading 'sendMessage') This shows that I'm not getting a response from the service worker, but I haven't been able to figure out why.

manifest.json:

{
    "manifest_version": 3,
    "name": "My extension",
    "description": "Full of bugs",
    "version": "0.1",
    "author": "SorkoEdu",
    "permissions": [
        "tabs"
    ],
    "background": {
        "service_worker": "background.js"
    },
    "icons": {
        "16": "images/icon-16.png",
        "32": "images/icon-32.png",
        "48": "images/icon-48.png",
        "128": "images/icon-128.png"
    },
    "content_scripts": [
        {
            "matches": ["<url match pattern here>"],
            "js": ["cs.js"],
            "world": "MAIN"
        }
    ],
    "host_permissions": [
        "<url match pattern here>"
    ],
    "action": {
        "default_icon": {
            "16": "images/icon-16.png"
        }
    }
}

cs.js:

...

console.log("sending message")
chrome.runtime.sendMessage({type: "tab"}, async function(tab){
    await asynchronousFunction(tab.id);
});

background.js:

chrome.runtime.onMessage.addListener(async function(request, sender, sendResponse) {
    console.log("received message");
    if (request.type === "tab") {
        let [tab] = await chrome.tabs.query({active: true, lastFocusedWindow: true})
        sendResponse(tab)
    }
    return true;
});

Any help would be appreciated. I've checked all over the internet to no avail.

EDIT: I've checked this answer, and I'm not having the same problem. My background.js returns a true value, which was the problem they were encountering in the other answer. Instead, my console.log("received message"); in the message reciever never runs.

SorkoEdu
  • 1
  • 3

0 Answers0