javascript - 本地主机上的 fetchApi Firefox 扩展
问题描述
我正在尝试构建一个简单的 firefox 扩展,它连接到本地 http 服务器并请求站点的权限。(服务器是一个带有 Cors Header 的 simpleHttp 服务器。)
--扩展代码--
allowed();
function allowed() {
r = window.location.href;
console.log("hi")
fetch('http://localhost:8081/site_x?s='+r,{
mode: "cors",
method: "GET",
headers: {
"Accept": "text/plain"
}})
.then((response) =>response.text())
.then((data) => {
if(data=="True"){
window.location.href = "https://www.yofla.com/black-screen/#";
}
})
.catch(error => {
console.log(error);
return error;
});
}
-- 我在 Firefox 控制台中遇到网络错误。
-- 主文件
{
"manifest_version": 2,
"name": "Productivity",
"version": "0.0.1b",
"description": "Some describtion",
"icons": {
"48": "icons/Logo48.png",
"96": "icons/Logo96.png"
},
"permissions": [
"activeTab",
"https://ipinfo.io/*",
"http://localhost:8081/*"
],
"content_scripts": [
{
"matches": [ "*://*/*" ],
"js": [ "jQuery-min-3.4.1.js","connect.js" ]
}
]
}
我认为这与权限有关,因为此代码适用于https://www.w3schools.com/code/tryit.asp?_______
解决方案
所以我将 fetch 移到后台脚本并在端口 80 上运行服务器,但仍然... // background-script.js
async function handleMessage(request, sender, sendResponse) {
let r = await fetch('http://127.0.0.1/site_x?s='+request.greeting,{
method: 'GET',
mode: 'cors',
headers: {
"Accept": "text/plain"
}
});
let data = await r.text();
sendResponse({response: data});
}
function normal(request, sender, sendResponse){
handleMessage(request, sender, sendResponse);
}
browser.runtime.onMessage.addListener(normal);
// 内容脚本.js
´´´
function handleResponse(message) {
console.log(`Message from the background script: ${message.response}`);
}
function handleError(error) {
console.log(`Error: ${error}`);
}
function notifyBackgroundPage(e) {
var sending = browser.runtime.sendMessage({
greeting: e
});
sending.then(handleResponse, handleError);
}
notifyBackgroundPage("test");
{
"manifest_version": 2,
"name": "Productivity",
"version": "0.0.1b",
"description": "Adds a red border to all webpages matching mozilla.org.",
"icons": {
"48": "icons/Logo48.png",
"96": "icons/Logo96.png"
},
"background": {
"scripts": ["background.js"]
},
"content_scripts": [
{
"matches": [ "*://*/*" ],
"js": [ "jQuery-min-3.4.1.js","connect.js" ]
}
],
"permissions": [
"activeTab",
"https://ipinfo.io/*",
"http://localhost/*",
"http://127.0.0.1/*",
"webNavigation"
]
}
推荐阅读
- c# - 如何设置 ASP.Net 3.0 Core Web API 项目以使用 AutoFac 和 NLog?
- visual-studio-2019 - ML.NET 图像分类训练冻结
- r - 如何在 R 中的多个图中绘制 ts?
- javascript - 在迭代中解决承诺
- html - 正确使用列表项中的视口单位
- elixir - DBConnection.ConnectionError PID(XXX) exited for some sql 查询
- java - 如何在同一线程中成功对第二个 Kafka 消费者执行轮询?
- python - 在 python 中使用 loc 进行布尔选择
- r - 在安装时生成 R 包的说明
- python - python3 for循环中的动态变量访问