mv3 chrome插件开发Unchecked runtime.lastError: Could not establish connection. Receiving end does not exist.
chrome.tabs.sendMessage(
//request.active_tab_id,
//tab_id: 2049247821
// popup.js:33 tab_id: 2049247756
// popup.js:33 tab_id: 2049247836
2049247756,
{message:"clear"}
// ,
// function(response) {// popup直接给contentscript发消息
// console.log(response);
// }
);
我自己测试的原因
1 tab id 不正确
2 加了回调函数 function(response)
3 特别注意,插件调试更新的时候 ,测试网页也要更新
4 backgoud.js 直接发送 tabs消息 ,也会报错 Could not establish connection. Receiving end does not exist
backgoud.js 直接发送 tabs消息 ,也会报错 Could not establish connection. Receiving end does not exist,需要popup页面激活,才能发送消息过去。
chrome.tabs.query({ active: true,currentWindow: true}, function(tabs) {
if (tabs.length > 0) {
let activeTab = tabs[0];
for (let i = 0; i < tabs.length; i++) {
console.log('b.js >> tab_id: ' + tabs[i].id); // 打印当前活动标签的信息
}
chrome.tabs.sendMessage(
//request.active_tab_id,
//tab_id: 2049247821
// popup.js:33 tab_id: 2049247756
// popup.js:33 tab_id: 2049247836
activeTab.id, {message:"background.js"}
// ,
// function(response) {// popup直接给contentscript发消息
// console.log(response);
// }
);
}});
如果popup没有激活
b.js >> tab_id: 2049248226
b.js:1 Uncaught (in promise) Error: Could not establish connection. Receiving end does not exist.
popup激活后 ,就是点开插件
收到了来自popup的消息:
b.js:27 {action: 'popupAction', data: 'message from popup'}
我的其他原因是 popup.js 一会发送到runttime 一会发 chrome.tabs.sendMessage
可能乱了,
解决办法:
1.我直接关闭了,所有的扩展,然后重新新建了 mv3项目,
2
chrome.tabs.query({ }, function(tabs) { if (tabs.length > 0) { let activeTab = tabs[0]; for(let i=0 ; i< tabs.length; i++ ){ console.log('tab_id: '+tabs[i].id); // 打印当前活动标签的信息 }});
全部输出所有的tab id比对
popup.js 加入下面代码就报错
chrome.tabs.sendMessage( activeTab.id, { from: 'popup', message: 'message' }, //sendResponse('has send') function(response) { if (response && response.data) { // 处理返回的数据 console.log(response.data); // 可以将数据显示在页面上或做其他处理 } else if (response && response.error) { // 处理错误 console.error(response.error); } } );
我看到其他文章mainfest.js
中
"matches": [ "http://*/*" ], 配置错误