Chrome扩展程序:如何将消息表格背景发送到后台?

问题描述:

我的后台监听器是

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

chrome.contextMenus.onClicked 听众中,我想要使用消息系统,我打电话

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.

那么,我如何将sendMessage从后台发送到后台?

So, how can I sendMessage from background to background ?

页面调度的邮件不会被同一页面收到。

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

如果您希望能够重新使用 onMessage 侦听器,请将其放在单独的函数中。例如:

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