从内容脚本发送消息到firefox webextension中的browseraction?

问题描述 投票:0回答:1

是否可以直接从内容脚本发送消息到浏览器操作而不使用后台页面?以下是我的代码的简化版本。内容脚本似乎工作正常,但我在控制台中收到以下错误:

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);
javascript firefox-addon firefox-webextensions
1个回答
-2
投票

您可以将弹出窗口中的消息发送到后台并获取响应以及来自后台的消息。这样,后台将知道弹出窗口存在,因此从后台到弹出窗口的消息将成功。

最新问题
© www.soinside.com 2019 - 2024. All rights reserved.