Chrome extension: How to sendMessage form background to background?
google-chrome, google-chrome-app, google-chrome-extension, javascript
Solution
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);
});
Problem
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 ?