javascript - 将消息从后台脚本发送到内容脚本(多个浏览器)
问题描述
我有一个可在 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”.
解决方案
我建议您使用https://github.com/mozilla/webextension-polyfill来实现跨浏览器兼容性。
推荐阅读
- android - 如何请求 GPS 定位许可以“始终允许”?
- amazon-s3 - Quicksight Athena - [Simba][AthenaJDBC](100071) AWS Athena 客户端引发错误
- c - 数组中的随机字符不重复
- javascript - Swiper 更改延迟加载的图像
- python-3.x - 如何使用 AWS python3 Lambda 将数据发送到 S3 存储桶?
- mysql - 如何旋转此源表
- python - Pandas:ValueError:工作表索引 0 无效,找到 0 个工作表
- java - 为什么屏幕尺寸看起来比实际尺寸大 android studio
- blazor - Blazor Desktop 读/写文件?
- java - 使用数据绑定时如何在适配器中绑定 viewModel