Chrome extension: How to sendMessage form background to background?

左心房为你撑大大i 提交于 2019-12-07 23:38:33

问题


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 ?


回答1:


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);
});



回答2:


I think you should use chrome.extension.onRequestExternal or chrome.extension.onConnectExternal



来源:https://stackoverflow.com/questions/17899769/chrome-extension-how-to-sendmessage-form-background-to-background

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!