Home > Blockchain >  Background script not receiving messages in chrome extension
Background script not receiving messages in chrome extension

Time:12-02

I have a chrome extension(MV3) that renders a react app, in the react app I send a message that should be received and handled in the background script.

Although the message is being published it does not being received in the listener I set in the background script.

When I try to listen to the message in the content script it does work, so I'm not sure what the problem is.
Is there an issue listening to messages in the background script?

background.ts -

chrome.runtime.onMessage.addListener(function (msg: any, sender: chrome.runtime.MessageSender, sendResponse: (response?: any) => void) {
    console.log('bg onMessage');
    if (msg.messageType === "USER_IDENTIFIED") {
        const accessToken = msg.content.accessToken;
        saveToStorage({accessToken});
        fetchSolution(sender.tab);

        sendResponse({
            response: "USER_IDENTIFIED Message Received"
        });
    }
    return true;
});

App.tsx (where I send the message) -

if (accessToken !== user.accessToken) { // We want to send USER_IDENTIFIED message only if accessToken changed
    console.log("Send user identified")
    new ChromeExtensionService().sendMessage("USER_IDENTIFIED", {accessToken: user.accessToken})
}

chrome-extension-service.ts -

export class ChromeExtensionService {
    async sendMessage(messageType: string, messageBody: object): Promise<void> {
        return new Promise<void>((resolve, reject) => {
            chrome.tabs.query({active: true, currentWindow: true}, (tabs) => {
                if (tabs.length === 0) {
                    reject("No open tabs to serve");
                }

                chrome.tabs.sendMessage(tabs[0].id!, {
                        messageType: messageType,
                        content: messageBody,
                    },
                    (response) => {
                        if (!response) {
                            reject("Something went wrong when sending the message to chrome extension");
                        }

                        console.log("Got a response - ", response);
                        resolve();
                    }
...

And again, if I do the same code that i have in the background script in the content script instead everything works.

Any ideas?

CodePudding user response:

I assume you're writing an MV3 extension.

chrome.tabs.sendMessage() can't send messages to the service worker, because the service worker does not have a tab. This is unlike MV2, where the background page is basically an invisible tab.

To send a message to the service worker, use chrome.runtime.sendMessage()

See chrome.runtime.sendMessage

Sends a single message to event listeners within your extension/app or a different extension/app. Similar to runtime.connect but only sends a single message, with an optional response. If sending to your extension, the runtime.onMessage event will be fired in every frame of your extension (except for the sender's frame), or runtime.onMessageExternal, if a different extension. Note that extensions cannot send messages to content scripts using this method. To send messages to content scripts, use tabs.sendMessage.

  • Related