Search code examples
javascriptgoogle-chromegoogle-chrome-extension

Background script's sendMessage isn't received in onMessage of a background script


I'm trying to break up the background script of a Chrome extension into smaller, more manageable individual scripts that communicate with each other via message passing. Right now I have two scripts background.js and database.js.

background.js

var message = 1;
console.log("Background.js running");
console.log("Sending message " + message);
chrome.runtime.sendMessage(message, function (response) {
    console.log("Response received " + response);
    message+=1;
})

database.js

console.log("Database.js running");
chrome.runtime.onMessage.addListener(function (request, requester, sendResponse) 
{
    console.log("message received " + request);
    console.log("Sending response " + request);
    sendResponse(request);
    return true;
});

They both run on startup and database.js registers a message listener.I then use sendMessage in database.js, hoping to receive and handle it in database.js. However, the callback for sending the message is called immediately, with an empty response, and the handler in database.js does not trigger.

When I run the extension with the above two scripts, I would like to see the output:

Database.js running
Background.js running
Sending message 1
Message received 1
Sending response 1
Response received 1

I instead get:

Database.js running
Background.js running
Sending message 1
Response received undefined

What causes this behavior and is it fixable?


Solution

  • According to documentation:

    If sending to your extension, the runtime.onMessage event will be fired in every frame of your extension (except for the sender's frame)

    You can't receive a message in the same frame/context it is sent. Like Daniel Herr pointed out, you can just call the functions you want instead of passing messages.