javascriptgoogle-chromegoogle-chrome-extension

No response to Fetch request in chrome extension background script


enter image description here

I'm trying to write a chrome extension to grab some stored data and POST it to a remote db table. I'm trying to testing the post functionality using https://www.postb.in/. I am using a devtools panel that I've added. I've stepped through the code and it seems to be working up until about line 37 in background.js. What am I doing wrong?

Panel.js contains:

const toDbBtn = document.getElementById("toDbBtn");

toDbBtn.addEventListener("click", async () => {
  const dbName = document.getElementById("textBox").value;

  try {
    const result = await chrome.storage.local.get(["yourKey"]);

    if (result.yourKey) {
      const savedArray = JSON.parse(result.yourKey);
      console.log(result.yourKey);
      console.log("Saved Array:", savedArray);
      console.log("DB Name:", dbName);
      console.log("Type of result.yourKey:", typeof result.yourKey);
      console.log("Type of savedArray:", typeof savedArray);
      console.log("Is savedArray an array?", Array.isArray(savedArray));

      // Send message to background script
      const response = await chrome.runtime.sendMessage({
        action: "sendToDB",
        data: { dbName: dbName, savedArray: result.yourKey },
      });

      if (response.error) {
        console.error("Error:", response.error);
      } else {
        console.log("Success:", response.result);
      }
    } else {
      console.log("No data found in storage to send.");
    }
  } catch (error) {
    console.error("Error during storage or message sending:", error);
  }
});

background.js:

chrome.runtime.onConnect.addListener(port => {});

chrome.runtime.onMessage.addListener(async (request, sender, sendResponse) => {
  if (request.action === "sendToDB") {
    const { dbName, savedArray } = request.data;

    if (typeof dbName !== 'string' || typeof savedArray !== 'string') {
      sendResponse({ error: 'Invalid data types' });
      return false;
    }

    let parsedArray;
    try {
      parsedArray = JSON.parse(savedArray);
    } catch (e) {
      sendResponse({ error: 'Invalid JSON string for savedArray' });
      return false;
    }

    const data = {
      dbName: dbName,
      savedArray: parsedArray,
    };

    const postable = JSON.stringify(data);
    console.log("postable", postable);

    try {
      const response = await fetch("https://www.postb.in/1743970496740-3388752799946", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: postable,
      });

      const result = await response.json();
      console.log("Response from server:", result);
      sendResponse({ result: result });
    } catch (error) {
      sendResponse({ error: error.message });
    }

    return true; // Required for asynchronous response
  }
  return false; // Required if the message is not for this listener
});

manifest.json:

{
  "manifest_version": 3,
  "name": "myDevTools",
  "version": "1.0",
  "description": "Description of your extension",
  "devtools_page": "devtools.html",

  "host_permissions": [
    "*://*.cnn.com/",
    "https://www.postb.in/*"
  ],
  "permissions": [
    "storage",
    "activeTab",
    "scripting",
    "webNavigation",
    "tabs",
    "unlimitedStorage",
    "cookies",
    "alarms",
    "notifications",
    "contextMenus",
    "offscreen",
    "identity",
    "identity.email",
    "nativeMessaging",
    "browsingData"
  ],
  "background": {
    "service_worker": "background.js"
  }
}

EDIT: I changed the POST request to:

const response = await fetch("https://www.postb.in/1743979363812-2128863274119", {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
      "Access-Control-Allow-Origin": "*",
      "Access-Control-Allow-Methods": "POST",
      "Access-Control-Allow-Headers": "Content-Type"
    },
    body: postable,
  });

enter image description here


Solution

  • Looks like you had to include Access-Control-Allow-Origin, et al. headers in your request, re the first comment I made here. You figured it out in code though.