是否可以直接从内容脚本向浏览器操作发送消息而无需使用后台页面?以下是我的代码的简化版本。内容脚本似乎工作正常,但我在控制台中收到以下错误:
Error: Error: Could not establish connection. Receiving end does not exist.
我假设是因为浏览器操作并非始终有效。但是我不想使用Background页面,因为我不希望脚本不断地运行内存。我希望直接向浏览器操作发送消息并显示一个弹出窗口,类似于browserAction.onClicked显示弹出窗口。这是我尝试构建的第一个扩展,所以试图解决问题。感谢
[的manifest.json]
{
"manifest_version": 2,
"name": "Test",
"version": "0.1",
"icons": {
"48": "icons/test.png"
},
"permissions": [
"activeTab"
],
"browser_action": {
"default_icon":"icons/test.png",
"default_title": "test",
"default_popup": "popup/popup.html",
"browser_style": true
},
"content_scripts": [
{
"matches": ["*://testwebsite"],
"js": ["content_scripts/content-script.js"]
}
]
}
[popup.js]
function handleMessage(request, sender, sendResponse) {
console.log("Message from the content script: " +
request.greeting);
sendResponse({response: "Response from background script"});
}
browser.runtime.onMessage.addListener(handleMessage);
[内容的script.js]
function handleResponse(message) {
console.log(`Message from the background script: ${message.response}`);
}
function handleError(error) {
console.log(`Error: ${error}`);
}
function send_2_popup() {
var sending = browser.runtime.sendMessage({
greeting: "Greeting from the content script"
});
sending.then(handleResponse, handleError);
}
var btn = document.getElementById("btn");
btn.addEventListener("click", send_2_popup);
答案 0 :(得分:-2)
您可以将消息从弹出窗口发送到后台并获取响应以及来自后台的消息。这样,后台将知道弹出窗口存在,因此从后台到弹出窗口的消息将成功。