我收到错误,无法建立从后台到内容的连接。我希望后台能够向内容页面的每个实例发送消息,以便为所有选项卡全局运行函数。任何帮助将不胜感激,因为我已经坚持了几个小时了。谢谢!
错误: 未捕获(承诺)错误:无法建立连接。接收端不存在。
内容.js:
// Message listener from background.js to execute a function in this content script
chrome.runtime.onMessage.addListener((message, _sender, _sendResponse) => {
if (message.action === "resetTimer") {
resetInactiveTimer();
}
});
背景.js:
if (message.action == "globalResetTimer") {
// Reset timer in all tabs
chrome.tabs.query({}, function (tabs) {
for (var i=0; i<tabs.length; ++i) {
chrome.tabs.sendMessage(tabs[i].id, { action: "resetTimer"});
}
});
}
manifest.json:
"content_scripts": [
{
"matches": ["<all_urls>"],
"js": ["content.js"],
"run_at": "document_start"
}
],
"background": {
"service_worker": "background.js"
},
我尝试了你的代码,它在 Chrome(版本 126)中对我有用。
所以你的扩展中肯定还做了其他事情。
您是否确保安装扩展后选项卡已打开/更新?如果在安装扩展之前打开网站,内容脚本将无法正确注入。
类似的问题是,如果您在扩展程序中的某个位置调用 chrome.runtime.reload()
但不重新加载要向其发送消息的选项卡。一种
替代方法,但这只适用于特定用例,即使用chrome.scripting.executeScript()
功能。