首页 > 解决方案 > 将消息从后台脚本发送到内容脚本(多个浏览器)

问题描述

我有一个可在 Chrome 上运行的扩展的工作原型,但是当我尝试在 Firefox 上运行它时,出现以下错误:

Unchecked lastError value: Error: Could not establish connection. Receiving end does not exist.

我使用此代码来区分浏览器:

window.namespace = (function () {
return window.msBrowser ||
    window.browser ||
    window.chrome;
})();

以下部分是检测用户何时单击扩展图标(以便我知道激活它):

let show_floater = false;          // to know if extension should be active

window.namespace.browserAction.onClicked.addListener(function(tab) {
    buttonClicked(tab);
});

function buttonClicked(tab) {
    show_floater = !show_floater;

    console.log('coding intensifies');

    // Send message to content_script of tab.id
    window.namespace.tabs.sendMessage(tab.id, show_floater);  // <-- ERROR IS HERE
}

所有这些代码都在我的后台脚本中。

我的内容脚本中对消息的处理如下

window.namespace.runtime.onMessage.addListener(gotMessage);

let injected = false;

function gotMessage(show_floater, sender, sendResponse) {
     // Here I just do stuff
     console.log("I'm working here!");
}

在网上我看到有这个问题的人通常不会在清单中包含 <all_urls> 。就我而言,我已经有了,所以我有点迷路了。据我了解,Chrome 和 Firefox 都应该使用相同的方法来发送和接收消息。我区分浏览器的方式有缺陷吗?

变化

在这里,我找到了解决方案。

背景:

chrome.browserAction.onClicked.addListener(function (event) {
    chrome.tabs.executeScript(null, {
        file: 'js/content.js', /* my content script */   }, () => {
        connect() //this is where I call my function to establish a 
connection     });
    });
});

function connect() {
    chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {
        const port = chrome.tabs.connect(tabs[0].id);

        show_floater = !show_floater;

        port.postMessage(show_floater);
        // port.onMessage.addListener((response) => {
        //     html = response.html;
        //     title = response.title;
        //     description = response.description;
        // });
    });

内容脚本:

chrome.runtime.onConnect.addListener((port) => {
     port.onMessage.addListener((show_floater) => {
          else if (!injected) {
           injected = true;

           let link = document.createElement("link");
           link.className = 'beebole_css';
           link.href = "https://localhost/css/test.css";
           link.type = "text/css";
           link.rel = "stylesheet";
           document.querySelector("head").appendChild(link);

           let s = document.createElement("script");
           s.className = 'beebole_js';
           s.src = "https://localhost/js/test.js";
           s.type = 'text/javascript';
           // document.body.appendChild(s);
           document.querySelector('body').appendChild(s);
      }
     });
});

同样,此代码在 Chrome 上完美运行,但在 Firefox 上它给出以下错误:

Loading failed for the <script> with source “https://localhost/js/test.js”.

标签: javascriptmessagefirefox-addon-webextensionscontent-script

解决方案


我建议您使用https://github.com/mozilla/webextension-polyfill来实现跨浏览器兼容性。


推荐阅读