简体   繁体   中英

WebExtension message from popup script to content script

I am new to Firefox extensions. I am trying to send a message from the popup script to the content script when a button is clicked, but I receive this error:

Could not establish connection. Receiving end does not exist.

I am not getting any other errors, so I am not sure why this error is occuring.

The popup script:

document.getElementById("rec").addEventListener("click", (e) => {
    var query = browser.tabs.query({currentWindow: true, active : true});
    var tab = query.then(getTab,onError);

    function getTab(tabs) {
        for (let tab of tabs){
            send(tab.id);
        }
    }

    function onError(error) {
      console.log(`Error: ${error}`);
    }

    function send(tab){
        browser.tabs.executeScript(tab, {
        file: "/content_scripts/recorder.js",})
        .then(function () { browser.tabs.sendMessage(tab, {record: "start"}) })
        .catch(console.error.bind(console));
    }
});

The content script:

(function() {
    if (window.hasRun) {
        return;
    }
    window.hasRun = true;

    browser.runTime.onMessage.addListener(notify);
    function notify(message){
        alert(message.record);
    }
})();

manifest.json:

{

  "manifest_version": 2,
  "name": "TW Recorder",
  "version": "1.0",

  "description": "Recorder.",

  "icons": {
    "48": "icons/border-48.png"
  },
  "permissions": [
    "<all_urls>",
    "activeTab",
    "tabs",
    "storage",
    "webRequest"
  ],
  "browser_action": {
    "default_icon": "icons/border-48.png",
    "default_title": "Recorder",
    "default_popup": "popup/main.html"
      },

  "content_scripts": [
    {
      "matches": ["<all_urls>"],
      "js": ["content_scripts/jquery-3.3.1.min.js","content_scripts/recorder.js"]
    }
  ]

}

The corrected content script (changed runTime to runtime):

(function() {
    if (window.hasRun) {
        return;
    }
    window.hasRun = true;

    browser.runtime.onMessage.addListener(notify);
    function notify(message){
        alert(message.record);
    }
})();

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