【问题标题】:WebExtension message from popup script to content script从弹出脚本到内容脚本的 WebExtension 消息
【发布时间】:2018-10-04 13:59:23
【问题描述】:

我是 Firefox 扩展的新手。单击按钮时,我尝试从弹出脚本向内容脚本发送消息,但收到此错误:

Could not establish connection. Receiving end does not exist.

我没有收到任何其他错误,所以我不确定为什么会发生此错误。

弹出脚本:

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

内容脚本:

(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"]
    }
  ]

}

【问题讨论】:

    标签: javascript firefox firefox-addon-webextensions content-script


    【解决方案1】:

    更正的内容脚本(将运行时更改为运行时):

    (function() {
        if (window.hasRun) {
            return;
        }
        window.hasRun = true;
    
        browser.runtime.onMessage.addListener(notify);
        function notify(message){
            alert(message.record);
        }
    })();
    

    【讨论】:

      猜你喜欢
      • 2020-10-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-08-31
      • 2017-12-24
      • 2013-10-12
      • 1970-01-01
      相关资源
      最近更新 更多