1. 简单示例
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
console.log('收到来自content-script的消息:');
console.log(request, sender, sendResponse);
sendResponse('我是后台,我已收到你的消息:' + JSON.stringify(request));
});
chrome.runtime.sendMessage({greeting: '你好,我是content-script呀,我主动发消息给后台!'}, function(response) {
console.log('收到来自后台的回复:' + response);
});
2. 封装
const POPUP_SCRIPT_MSG = 'popupScriptMsg';
export const PopupScript = {
send({ type, data, cb }) {
if (chrome && chrome.tabs && chrome.tabs.query && chrome.tabs.sendMessage) {
chrome.tabs.query({ active: true, currentWindow: true }, function (tabs) {
chrome.tabs.sendMessage(tabs[0].id, { uri: POPUP_SCRIPT_MSG, type, data }, (res) => {
cb && cb(res);
});
});
}
}
};
const contentHanders = {};
export const ContentScript = {
isInit: false,
init() {
if (chrome && chrome.runtime && chrome.runtime.onMessage && chrome.runtime.onMessage.addListener) {
chrome.runtime.onMessage.addListener(async function (request, sender, sendResponse) {
const { uri, data, type } = request;
if (uri == POPUP_SCRIPT_MSG) {
const cb = contentHanders[type];
cb && cb(data, sendResponse);
}
});
}
},
on(type, cb) {
if (!this.isInit) {
this.init();
}
contentHanders[type] = cb;
}
};
使用
import { PopupScript } from 'connect.js';
PopupScript.send({
type: 'getInitConf',
data: {},
cb: res => {
console.log(res);
}
});
import { ContentScript } from 'connect.js';
ContentScript.on('getInitConf', (data, cb) => {
cb({a: data});
});