从内容脚本发送消息到浏览Firefox的webextension?

问题描述:

是否可以直接从内容脚本向浏览器操作发送消息而不使用后台页面?以下是我的代码的简化版本。内容脚本似乎是做工精细,但我在控制台中出现以下错误:从内容脚本发送消息到浏览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); 
+0

“这是因为浏览器操作不总是处于活动状态” - >您似乎回答了您自己的问题。你究竟在做什么*问。是的,为了使弹出窗口能够接收*存在*的内容。如果弹出窗口未打开,则不存在。 – Makyen

+0

如果没有背景页面,你不能做你想做的事。没有能力以编程方式打开实际的扩​​展弹出窗口。但是,你可以伪造它。请参阅[如何创建全局热键以打开Firefox(WebExtensions)中的“browserAction”弹出窗口)中的“打开伪弹出窗口”部分?](https://*.com/a/40296092) – Makyen

+0

谢谢获取信息。这很糟糕,你必须让后台脚本运行以占用资源。 –

可以而是来自发送消息弹出的背景,并得到一个响应以及从背景的消息..这种方式后台会知道弹出存在和母鸡从背景到弹出消息将成功。