首页 > 解决方案 > 本地主机上的 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?_______

标签: javascriptgoogle-chrome-extensionfirefox-addonfetch-api

解决方案


所以我将 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"
  ]

}

推荐阅读