简体   繁体   中英

Sending message from content script to browseraction in firefox webextension?

Is it possible to send a message from Content script to Browser action directly without using background page? Following is a simplified version of what my code looks like. The content script seems to be working fine, but I get the following error in the console:

Error: Error: Could not establish connection. Receiving end does not exist.

I am assuming it's because the Browser action is not always active. But I don't want to use a Background page because I don't want the script running constantly hogging memory. I am hoping to send message directly to Browser action and display a popup, sort of like browserAction.onClicked displaying a popup. This is my first extension that I am trying to build, so trying to figure things out. Thanks

[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);

[content-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);

您可以宁愿从弹出窗口向后台发送消息,也可以从后台获取消息以及响应。通过这种方式,后台将知道弹出窗口存在,因此从后台到弹出窗口的消息将会成功。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM