Messages not flowing correctly between Chrome extension background pages
I'm trying to break the background script of a Chrome extension into smaller, more manageable, separate scripts that communicate with each other via messaging. 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 run on startup and database.js
log a list of messages. Then I use sendMessage in database.js
, hoping to receive and process it in database.js
. However, the callback to send the message is called immediately, with an empty response, and the handler is database.js
not triggered.
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
Instead, I get:
Database.js running
Background.js running
Sending message 1
Response received undefined
What causes this behavior and can it be fixed?
source to share
According to the documentation :
When dispatched to your extension, the runtime.onMessage event will be ( except for the sender frame )
You cannot receive the message in the same frame / context that it sent. As Daniel Herr pointed out, you can just call the functions you want instead of passing messages.
source to share