Chrome扩展程序:如何将消息表格背景发送到后台? [英] Chrome extension: How to sendMessage form background to background?

查看:107
本文介绍了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);
});

这篇关于Chrome扩展程序:如何将消息表格背景发送到后台?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆