将消息从后台脚本发送到内容脚本(多个浏览器)



我有一个在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;
// });
});

contentscript:

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”.

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

最新更新