我正在尝试从 popup.js 向 content.js 脚本发送消息,但 content.js 脚本未收到该消息。 content.js 似乎没有从弹出窗口或后台脚本接收消息。
popup.js
window.onload = function() {
browser.tabs.query({active: true, currentWindow: true}, function(tabs) {
browser.tabs.sendMessage(tabs[0].id, { greeting: "hello from the popup" });
browser.runtime.sendMessage({ tabId: tabs[0].id, greeting: "Going to background?"});
debugger;
});
}
内容.js
browser.runtime.onMessage.addListener((request, sender, sendResponse) => {
console.log("Received request: ", request);
return true;
});
background.js——这个确实收到了消息
browser.runtime.onMessage.addListener((request, sender, sendResponse) => {
console.log("Received request in the bg: ", request);
browser.tabs.sendMessage(request.tabId, "Sent from bg");
});
manifest.json
{
"manifest_version": 3,
"name": "__MSG_extension_name__",
"description": "__MSG_extension_description__",
"version": "1.0",
"background": {
"scripts": [ "background.js" ],
"type": "module"
},
"content_scripts": [{
"js": [ "content.js" ],
"matches": [ "*://*/*" ],
"run_at": "document_end",
}],
"action": {
"default_popup": "popup.html",
"default_icon": "images/toolbar-icon.svg"
},
"permissions": [
"activeTab",
"nativeMessaging"
]
}
我注意到你的清单版本是3;然而,MV3 上不再有背景脚本了。让我们尝试 MV2,看看您的内容脚本是否收到消息。