使用页面直接通信到后台前需要先设置权限,在manifest中添加"externally_connectable": {“matches”: ["* 😕/.example.com/"]}
注意:externally_connectable里的匹配不能使用完全通配符,必须写根域名否则会报错
后台接收消息
chrome.runtime.onMessageExternal.addListener(
function(request, sender, sendResponse) {
console.log(request); // 发送的消息
console.log(sender); // 发送者的信息,tabs相关信息
// console.log(sendResponse); // 回调函数,回调给发送者的
sendResponse(sender);// 这里将tab信息发送给发送者
});
web发送消息和处理回调
/**
* 参数1(字符串): 插件ID
* 参数2(可对象): 发送的消息
* 参数3(函数):回调函数,处理后台返回的消息
*/
chrome.runtime.sendMessage(参数1, 参数2, function(response) {
console.log(response);
});