CHROME插件开发之·web页面与插件后台通信(chrome.runtime.sendMessage => chrome.runtime.onMessageExternal.addListener)
使用页面直接通信到后台前需要先设置权限,在manifest中添加"externally_connectable": {“matches”: ["* ????/.example.com/"]}注意:externally_connectable里的匹配不能使用完全通配符,必须写根域名否则会报错后台接收消息chrome.runtime.onMessageExternal.addListener(func
·
使用页面直接通信到后台前需要先设置权限,在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);
});
此外还可以用postMessage进行通信
魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。
更多推荐





所有评论(0)