我正在构建一个 Chrome 扩展。我尝试将消息从background.js(服务工作者)发送到content.js(内容脚本),我在background.js控制台中遇到了上述错误,但在content.js控制台收到了消息。解释如何修复错误以及如何发送消息。
背景.js
chrome.runtime.onMessage.addListener((message, sender , sendMessage)=>{
if(message.action == "changeTabColor"){
chrome.tabs.query({},(tabs)=>{
console.log(tabs);
tabs.forEach((tab) => {
chrome.tabs.sendMessage(tab.id, {action: "changeTabColor"});
});
})
}
})
console.log(
"background script"
)
内容.js
console.log("content script working fine ");
chrome.runtime.onMessage.addListener((message, sender, sendMessage) => {
if (message.action == "changeTabColor") {
console.log("button pressed ");
document.body.style.backgroundColor = 'lightblue';
}})
清单.json
{
"name": "club-tab",
"description": "to club active tabs",
"version": "1.0.0",
"manifest_version": 3,
"background": {
"service_worker": "background.js",
"type": "module"
},
"action": {
"default_popup": "popup.html"
},
"content_scripts": [
{
"matches": ["<all_urls>"],
"js": ["content.js"]
}
],
"permissions": ["tabs", "activeTab"],
"host_permissions": ["http://*/*", "https://*/*"]
}
在 Chrome 中,您需要在重新加载/安装扩展程序后重新注入内容脚本。但是,某些选项卡(例如 chrome://
(包括新选项卡)或
chrome-extension://
)无法运行内容脚本,因此 sendMessage 无论如何都会显示错误。你可以这样抑制它:
chrome.tabs.sendMessage(tab.id, {action: "changeTabColor"}).catch(() => {});