ChemPal Documentation - v1.6.0
    Preparing search index...
    • Performs an HTTP request from the extension's background service worker instead of the calling context, then reconstructs a real Response from the serialized reply.

      Use this when a page-context fetch is blocked by CORS: the worker is exempt from page CORS as long as the target host is listed in the manifest host_permissions. The returned Response works like a normal one for text/JSON bodies (.ok, .status, .text(), .json()); binary bodies are not supported.

      Parameters

      Returns Promise<Response>

      A Response reconstructed from the worker's reply.

      Error if the worker reports a fetch failure or returns an unrecognized reply.

      // GET reading text
      const res = await backgroundFetch("https://example.com/");
      const html = await res.text();

      // POST with a JSON body reading JSON
      const res2 = await backgroundFetch("https://api.example.com/search", {
      method: "POST",
      headers: { "content-type": "application/json" },
      body: JSON.stringify({ q: "acid" }),
      });
      if (res2.ok) {
      const data = await res2.json();
      }
      export async function backgroundFetch(url: string, init?: BackgroundFetchInit): Promise<Response> {
      const message: BackgroundFetchMessage = {
      type: MESSAGE_TYPE.BACKGROUND_FETCH,
      url,
      init: init ? { ...init, headers: normalizeHeaders(init.headers) } : undefined,
      };

      const result: BackgroundFetchResult = await chrome.runtime.sendMessage(message);

      if (isBackgroundFetchSuccess(result)) {
      return new Response(result.body, {
      status: result.status,
      statusText: result.statusText,
      headers: result.headers,
      });
      }

      const reason =
      typeof result === 'object' && result !== null && 'error' in result
      ? result.error
      : 'Unknown background fetch failure';
      throw new Error(`backgroundFetch| ${reason}`);
      }