Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Chrome extension: How to sendMessage form background to background?

My background listener is

chrome.runtime.onMessage.addListener(function (request, sender, sendResponse)

In chrome.contextMenus.onClicked listener, I want to use the message system,I call

chrome.runtime.sendMessage

in the listener, but it's not works.

So, how can I sendMessage from background to background ?

like image 615
wener Avatar asked Sep 10 '25 21:09

wener


1 Answers

Messages dispatched by a page are not received by the same page.

If you want to be able to re-use the onMessage listener, put it in a separate function. For example:

function alwaysDoSomething() {
    console.log('Done something!');
}
chrome.runtime.onMessage.addListener(function(message, sender, sendResponse) {
    alwaysDoSomething();
});
chrome.contextMenus.onClicked.addListener(function(info, tab) {
    alwaysDoSomething();
});

There is an undocumented method that can be used to manually trigger the events. It is undocumented, so use it at your own risk!

chrome.contextMenus.onClicked.addListener(function(info, tab) {
    var message = 'whatever';
    var sender = {tab: null, id: chrome.runtime.id};
    var sendResponse = function() {};
    chrome.runtime.onMessage.dispatch(message, sender, sendResponse);
});
like image 103
Rob W Avatar answered Sep 13 '25 09:09

Rob W