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?