我制作了这个简单的消息传递示例 chrome 扩展,其中应该将消息从后台脚本发送到内容脚本。不幸的是,内容脚本似乎没有收到该消息。
后台脚本:
// background.js
function sendMessage(tabId, hostname) {
console.log("Sending message to tabId: ", tabId)
chrome.tabs.sendMessage(tabId, {hostname: hostname}, (resp) => {console.log("response: ", resp)});
}
chrome.tabs.onUpdated.addListener((tabId, changeInfo, tab) => {
if (changeInfo.url) {
console.log(changeInfo.url)
var hostname = new URL(changeInfo.url).hostname;
sendMessage(tabId, hostname)
}
});
内容脚本:
// content.js
console.log("injected");
function logMessage(message) {
console.log("Message from background: ", message)
}
chrome.runtime.onMessage.addListener(
(request, sender, sendResponse) => {
logMessage(request.hostname)
}
);
清单(v3):
// manifest.json
{
"name": "Messaging test",
"description": "",
"version": "1.0",
"manifest_version": 3,
"background": {
"service_worker": "background.js"
},
"permissions": ["tabs"],
"content_scripts": [
{
"matches": [
"<all_urls>",
"https://*/*",
"http://*/*"
],
"js": ["content.js"]
}
]
}
我确保重新加载扩展并使用新选项卡进行测试。
以下是后台脚本的开发控制台输出:后台脚本的开发控制台输出 https://i.stack.imgur.com/NJJtf.png
这是内容脚本的开发控制台输出(注入 google.com):内容脚本的开发控制台输出 https://i.stack.imgur.com/9s7ue.png
因此,内容脚本被注入,但没有从后台脚本接收消息。我记得这在清单 v2 中工作,所以我不确定出了什么问题。有任何想法吗?