【2023-03-19】mv3 popup通信错误 checked runtime.lastError: Could not establish connection

以下脚本就是错误所在

这里可以通过打印当前界面的标签ID
作用:popup.jscontent.js 通信
效果:需要看到它们能正常通信(但切发生了错误,此时程序界面错误信息也提供大致方向信息)
注意:这里是自己所见的错误之仅供参考

chrome.tabs.query({ active: true, currentWindow: true }, function (tabs) {
	console.log("<popup 界面 ID>", tabs[0].id);
	chrome.tabs.sendMessage(tabs[0].id, {}, function (response) {
		console.log(response, 'content.js回传过来的信息');
	});
});

1、popup 界面

红线:popup.jsbackground.js通信
黄线:获取当前界面的标签ID
绿线:从storagelocal获取contentID,这就正常可以跟content.js通信啦

在这里插入图片描述

2、background 界面

content.js界面也是同上图中的红线一样向background.js通信的
就看到两条绿线的位置,那里就是利用storage存储对应的标签啦

在这里插入图片描述

3、解决问题

图一中绿线指向的脚本就是可以正常通信的
原因:background.js可以使用以下脚本能获取content.js标签ID,popup.js获取的却是自个界面的标签ID

// Background 界面
chrome.tabs.query({ active: true, currentWindow: true }, function(tabs) {
  console.log("<Background 界面 ID>", tabs[0].id);
   // chrome.tabs.sendMessage(tabs[0].id, {}, function (response) {
   // 	console.log(response, 'content.js回传过来的信息');
   // });
 });
 



// popup 界面 --------------------------------------------------------------------------------
/* `background.js` 通信 */
chrome.runtime.sendMessage({ name: "popup" },
	async (response) => {
		console.log(
			`<🚀 chrome.runtime.sendMessage> [popup.js]响应 >>>
			\n\r response:${JSON.stringify(response)}`
		);
	}
);

/** 
 * `popup.js`向`content.js` 通信
 * 注意:在popup页面需要查找当前激活的tabs
 * https://mp.weixin.qq.com/s/32YMmbfjAxl2JWcqDXfx0A
 */
chrome.tabs.query({ active: true, currentWindow: true }, function (tabs) {
	console.log("<popup 界面 ID>", tabs[0].id);
	// chrome.tabs.sendMessage(tabs[0].id, {}, function (response) {
	// 	console.log(response, 'content.js回传过来的信息');
	// });
});


chrome.storage.local.get(["contentID"], ({ contentID }) => {
	console.log("<获取local存储> [contentID]", contentID);
	/* `popup.js` 通信 */
	chrome.tabs.sendMessage(
		contentID,
		{ name: `popup` },
		async (response) => {
			console.log(
				`<🚀 chrome.tabs.sendMessage> [popup.js]响应 >>>
						\n\r response:${JSON.stringify(response)}`
			);
		}
	);
});