我正在使用清单 v3 做一个 chrome 扩展项目。
我尝试遵循网络上提出的不同教程/类似问题,但无法解决该错误。
目前,background.js 可以按照预期向 content.js 发送消息。但我还是想解决这个错误。任何帮助将不胜感激!
错误:
Uncaught (in promise) Error: Could not establish connection. Receiving end does not exist.
背景:
scripts/background.js
堆栈跟踪
scripts/background.js:0 (anonymous function)
我的代码: 清单.json
{
"manifest_version": 3,
"name": "YT Extension",
"description": "Youtube extension",
"version": "1.0.0",
"icons": {
"16": "assert/icons/icon16.jpeg",
"32": "assert/icons/icon32.jpeg",
"48": "assert/icons/icon48.jpeg",
"128": "assert/icons/icon128.jpeg"
},
"background": {
"service_worker": "./scripts/background.js",
"type": "module"
},
"content_scripts": [ {
"matches":["<all_urls>"],
"run_at": "document_end",
"js": ["./scripts/contentScript.js"]
} ],
"action": {
"default_popup": "popup.html"
},
"host_permissions": [
"https://www.youtube.com/*"
],
"permissions": [
"storage",
"tabs"
]
}
脚本/background.js
chrome.tabs.onUpdated.addListener((tabId, changeInfo, tab) => {
if (changeInfo.status === 'complete') {
console.log("background.js running...")
if (tab.url && tab.url.includes("youtube.com/watch")) {
console.log("Sending message: VIDEO")
chrome.tabs.sendMessage(tabId, {
type: "VIDEO",
});
}
else if (tab.url && tab.url.includes("youtube.com/")) {
console.log("Sending message: MAIN")
chrome.tabs.sendMessage(tabId, {
type: "MAIN",
});
}
else {
console.log("Sending message: NOT SUPPORTED")
chrome.tabs.sendMessage(tabId, {
type: "NOT SUPPORTED",
});
}
}
}
)
脚本/contentScript.js
chrome.runtime.onMessage.addListener((obj, sender, response) => {
const { type } = obj;
console.log("content.js running...")
if (type === "VIDEO") {
console.log("Received message: VIDEO")
}
else if (type === "MAIN") {
console.log("Select video")
}
else if (type === "NOT SUPPORTED") {
console.log("Website not supported")
}
}
);
您的扩展程序按预期工作,由于安全原因,当消息发送到未设置侦听器的选项卡(可能是
chrome://extension
)时,会发生错误。
因此,您必须识别生成此错误的选项卡并添加如下逻辑:
背景.js
chrome.tabs.onUpdated.addListener((tabId, changeInfo, tab) => {
if (changeInfo.status === 'complete') {
console.log("background.js running...");
if (!tab.url.startsWith("chrome://")) {
//...
}
}
});