chrome浏览器插件/扩展开发之popup与background通信
chrome浏览器插件/扩展开发之popup与background的双向通信,这块东西太杂,看文档折腾了一天。。。做个记录吧。
popup.js
const sendMessage = ({ type, data, callback }) => {
chrome.tabs.query({ active: true, currentWindow: true }, function (tabs) {
const tabId = tabs[0].id;
const port = chrome.tabs.connect(tabId, { name: 'NetWatchConn' });
// 这里顺带监听了消息并执行回调
port.onMessage.addListener((evt) => {
// console.log('[NetWatch]: popup.js onMessage', evt.type, evt);
if (callback && evt.type == type) {
callback(evt.data);
}
});
port.postMessage({ type, data, callback });
});
}
// 从content_scripts获取状态
sendMessage({
type: 'getStatus',
data: {},
callback: (data) => {
// console.log('[NetWatch]: getStatus ', data);
const { running } = data;
setRuningMsg(running);
}
});
background.js
let running = false;
chrome.runtime.onConnect.addListener((port) => {
console.log('[NetWatch]: connect to content_scripts', port);
// const sendMessage = port.postMessage;
port.onMessage.addListener((evt, sender) => {
const {type, data, callback} = evt;
// const sendMessage = sender.postMessage;
console.log("In background script, received message", type, data);
switch (type) {
case 'getStatus':
port.postMessage({type, data: {running}});
break;
case 'start':
running = true;
port.postMessage({type, data: {running}});
break;
case 'stop':
running = false;
port.postMessage({type, data: {running}});
break;
}
});
});