这个错误通常是因为背景脚本与内容脚本之间的通信出错造成的。解决方法是确保在内容脚本中正确发送消息给背景脚本,并保证背景脚本正确监听消息。
以下是一个示例,展示如何在内容脚本中发送消息给背景脚本并接收响应:
// 在内容脚本中发送消息给背景脚本 chrome.runtime.sendMessage({greeting: "hello"}, function(response) { console.log(response.farewell); });
// 在背景脚本中监听消息并发送响应 chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) { if (request.greeting == "hello") { sendResponse({farewell: "goodbye"}); } });
确保在您的代码中正确使用chrome.runtime.sendMessage和chrome.runtime.onMessage,以避免“未能建立连接”错误。