1 year ago

#351097

test-img

Rodrigo Yanez

Error with Chrome Extension sending message from background to content script

I'm learning about Chrome Extensions and I want to send a message from the background to a content script. I'm trying to do the simplest example, but I keep getting the following error:

Error in event handler: TypeError: Cannot read properties of undefined (reading 'id') at sendMessageBackgroundToScript (chrome-extension://ibghimmhcpdahopejafegpkgfcijmcin/event.js:4:35)

This is the code:

manifest.json:

{
    "name": "Send Messages",
    "description": "An example of how to send messages from background to script",
    "version": "1.0",
    "manifest_version": 3,
    "background": {
        "service_worker": "event.js"
    },
    "action": {
        "default_title": "Send Message",
        "default_icon": "images/icon32.png"
    },
    "permissions": [
        "scripting"
    ],
    "content_scripts": [
        {
            "matches": ["<all_urls>"],
            "js": ["script.js"]
        }
    ]

}

event.js:

chrome.action.onClicked.addListener(sendMessageBackgroundToScript);

function sendMessageBackgroundToScript(tabs) {
  chrome.tabs.sendMessage(tabs[0].id, {text: "This is a message"})
}

script.js:

chrome.runtime.onMessage.addListener(gotMessage);

function gotMessage(message, sender, sendResponse) {
  console.log(message.text);
}

javascript

google-chrome-extension

service-worker

sendmessage

content-script

0 Answers

Your Answer

Accepted video resources