0
是否可以直接從內容腳本向瀏覽器操作發送消息而不使用後臺頁面?以下是我的代碼的簡化版本。內容腳本似乎是做工精細,但我在控制檯中出現以下錯誤:從內容腳本發送消息到瀏覽Firefox的webextension?
Error: Error: Could not establish connection. Receiving end does not exist.
我假設這是因爲瀏覽器的行動並不總是積極的。但我不想使用後臺頁面,因爲我不希望腳本不斷地佔用內存。我希望直接發送消息給瀏覽器動作並顯示一個彈出窗口,有點像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);
「這是因爲瀏覽器操作不總是處於活動狀態」 - >您似乎回答了您自己的問題。你究竟在做什麼*問。是的,爲了使彈出窗口能夠接收*存在*的內容。如果彈出窗口未打開,則不存在。 – Makyen
如果沒有背景頁面,你不能做你想做的事。沒有能力以編程方式打開實際的擴展彈出窗口。但是,你可以僞造它。請參閱[如何創建全局熱鍵以打開Firefox(WebExtensions)中的「browserAction」彈出窗口)中的「打開僞彈出窗口」部分?](https://stackoverflow.com/a/40296092) – Makyen
謝謝獲取信息。這很糟糕,你必須讓後臺腳本運行以佔用資源。 –