前言
语法
chrome.runtime.onMessage.addListener(
callback: function,
)
callback
参数如下:
参数 | 类型 | 说明 |
---|---|---|
request | Any | 包含发送者的信息和请求的内容 |
sender | MessageSender | 包含发送者的详细信息 |
sendResponse | Function | 是一个可以用来向发送者发送响应的函数 |
基本示例
chrome.runtime.onMessage.addListener(
function(request, sender, sendResponse) {
console.log(sender.id + " 发送了请求:" + request.data);
// 你可以在这里处理接收到的消息
// 如果需要,你可以通过 sendResponse 函数发送响应给发送者
// sendResponse({data: "回复消息"});
}
);
在这个例子中,我们监听来自任何发送者的消息;
每当有消息发送时,监听函数(callback
)就会被调用;
注意
封装
示例
const listenerList = {
token: function({ request, response }){
// code...
},
/**
* 创建与项目的共享变量数据
*/
createPluginVariable: function({ request, response }){
let name = SystemEnum.APP_PLUGIN_KEY;
let value = '1';
let _cf = {url: SysConfig.APP_URL, name}
chrome.cookies.remove(_cf,function (res) {
_cf.domain = SysConfig.APP_DOMAIN;
_cf.value = value;
_cf.expirationDate = new Date().setDate(new Date().getDate() + 7);
chrome.cookies.set(_cf, function (res) {
response({name, value, config: request, res})
});
});
}
};
const message = new MessageListener();
for (let messageKey in listenerList){
message.addListener(messageKey, listenerList[messageKey]);
}
message.start();
// content script脚本中发送消息
// chrome.runtime.sendMessage({contentRequest:'createPluginVariable'}, ()=>{})
实现
class MessageListener {
/**
* @var chrome.runtime.onMessage|null
*/
_message
/**
* @var Object
*/
_listener
constructor() {
this._listener = {}
this._message = chrome.runtime.onMessage || null
return {
addListener: (messageKey, request) => this.addListener(messageKey, request),
start: () => this.start(),
}
}
addListener(messageKey, request) {
this._listener[messageKey] = request
}
start() {
if (!this._message) return
let that = this
that._message.addListener(function (request, sender, response) {
return (
chrome.tabs.query({ currentWindow: !0, active: !0 }, function () {
if (!!that._listener[request.contentRequest]) {
that._listener[request.contentRequest]({
request,
response,
})
}
}),
!0
)
})
}
}
Chrome Developers官方接口文档:
- chrome.runtime.onMessage.addListener