Webextension: message passing between a service worker and a web page

1,072 views
Skip to first unread message

Giacomo Tommaso Petrucci

unread,
Jun 9, 2022, 4:11:44 AM6/9/22
to Chromium Extensions
Hello everyone,

I'm writing a web extension for Chromium and I'm using a service worker to do some background activities (something that with manifest V2 would have been done using a BackgroundScript). I need to send messages from a script that is injected into a web page to the service worker and get responses back. To do this, inside the injected script I use chrome.runtime.sendMessage like this:

chrome.runtime.sendMessage(extensionID,
{
content: emailBody,
identifiers: recipientsAddressesArray,
request: "encrypt"
}, (response)=>console.log("Got response: ", response)
)

While inside the service worker i have the following code:

import {encrypt, decrypt, getHiddenPolicies} from "./crypto";

chrome.runtime.onMessage.addListener((msg, sender, sendResponse) => {

    console.log("Message listener invoked")
})

console.log("Service worker started!")

Now, when the message is sent from the page to the service worker, I get "Got response:  undefined" in the page's console regardless of whether I write code in the message handler to send a response back or not, while if I inspect the service worker output using the devtools, I see "Service worker started!" and some output form the script I'm importing, but no "Message listener invoked". What I'm getting wrong?

Thank you for your help,

Giacomo

Giacomo Tommaso Petrucci

unread,
Jun 9, 2022, 4:36:37 AM6/9/22
to Chromium Extensions, Giacomo Tommaso Petrucci
Sorry, I found the problem: I have to use chrome.runtime.onMessageExternal.addListener instead of chrome.runtime.onMessage.addListener. I would suggest to have the case of service workers explicitly covered in the docs about message passing here: https://developer.chrome.com/docs/extensions/mv3/messaging/
Now I still have something not working but maybe it's unrelated to message passing, I'll open a new discussion if I need help.
Thanks,

Giacomo

Reply all
Reply to author
Forward
0 new messages