0

With the change of Manifest V3 coming in for Chrome Extensions I'm updating all XHR requests to now use the fetch API as instructed.

The background of a Chrome Extension is now a Service Worker and can become inactive and the use of setTimeout and setInterval is now being discouraged by chrome (https://developer.chrome.com/docs/extensions/mv3/migrating_to_service_workers/#alarms)

I'm trying to work out how I can abort a long running request if now the background service worker can go to sleep using the code below;

function generateAbortingAboutController(timeoutInMilliseconds) {
    const controller = new AbortController();

    setTimeout(() => {
        controller.abort();
    }, timeoutInMilliseconds);

    return controller;
}

function sendFetchRequest(type, url, data, contentType, dataType, onSuccess, onError) {

    const abortController = generateAbortingAboutController(100000);

    fetch(url, {
            method: type,
            body: data,
            headers: {
                "Content-Type": contentType
            },
            signal: abortController.signal
        })
        .then((response) => {
            if (response.ok) {
                return response.json();
            } else {
                throw response;
            }
        })
        .then((json) => {
            onSuccess(json);
        })
        .catch((e) => {
            if (e?.name === "AbortError") {
                return;
            }
            onError();
        });

    return abortController;
}

Is there a good practice on how to abort a long running request?

r0bb077
  • 732
  • 2
  • 11
  • 33
  • Service worker doesn't "go to sleep" or "become inactive" when its time is up. It is just terminated, along with all the network requests, timers, variables, etc. There's no need to cancel any of that explicitly. The default lifetime is 30 seconds. You can prolong it as shown in [Persistent Service Worker in Chrome Extension](https://stackoverflow.com/a/66618269) – wOxxOm Aug 18 '22 at 15:07
  • @wOxxOm Thanks! Where did you get your info about default lifetime of the service worker? – r0bb077 Sep 02 '22 at 01:39
  • 1
    It's mentioned in some documentation probably. Also in the [source code](https://crsrc.org/third_party/blink/public/mojom/service_worker/service_worker.mojom;l=149;drc=3b34399247d1e59327251bcc9f55badd7e932197). – wOxxOm Sep 02 '22 at 05:46

0 Answers0