0

I am creating a Chrome extension and try to fetch data from a server inside of addEventListener when a button is clicked. I get an error Uncaught (in promise) TypeError: Failed to fetch at request. I tried to run the request in a separate file with node file.js and it worked. I thought that I eventually need to add a permission inside of manifest.json for fetching data from a server but I cannot find any ressources for that. How can I fetch data from a server in a Chrome extension?

content.js

document.addEventListener("click", (event) => {
  if (event.target.innerText == "Reply") {
    console.log("reply clicked");
    function request(email) {
      let _data = {
          prompt: email,
      }
      fetch('fetch_address', {
          method: "POST",
          body: JSON.stringify(_data),
          headers: {"Content-type": "application/json; charset=UTF-8"}
      })
      .then(response => response.json()) 
      .then(json => console.log(json['response']));
    }
    request('this is a test message to check the API');
  }
});

background.js

console.log("background.js loaded");
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
  console.log("message received in background.js");
  if (request.type == "click_event") {
    console.log("click event captured in current webpage");
  }
});

Max Hager
  • 536
  • 4
  • 13
  • Are you aware your fetch request says ```fetch('fetch_address', {``` ... the string "fetch_address" would definitely fail regardless of whether its a chrome extension or not. If you get a CORS error, that is a different problem and would be solved differently. – Jridyard Dec 13 '22 at 00:59
  • [This](https://stackoverflow.com/a/55292071/14606987) post made me understood the issue, thanks. `fetch_address` was just a placeholder for the real one. @Jridyard – Max Hager Dec 13 '22 at 01:09

0 Answers0