fetchApi Firefox расширение на локальный хост - PullRequest
0 голосов
/ 09 апреля 2020

Я пытаюсь создать простое расширение firefox, которое подключается к локальному http-серверу и запрашивает разрешения для сайта. (Сервер представляет собой простой HTTP-сервер с заголовком Cors.)

- код расширения -

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?_______

1 Ответ

0 голосов
/ 10 апреля 2020

Поэтому я перенес выборку в фоновый скрипт и запустил сервер на порту 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);

// content-script. 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"
  ]

}
...