files/en-us/web/api/serviceworkerglobalscope/index.md
{{APIRef("Service Workers API")}}{{SecureContext_Header}}{{AvailableInWorkers("service")}}
The ServiceWorkerGlobalScope interface of the Service Worker API represents the global execution context of a service worker.
Developers should keep in mind that the ServiceWorker state is not persisted across the termination/restart cycle, so each event handler should assume it's being invoked with a bare, default global state.
Once successfully registered, a service worker can and will be terminated when idle to conserve memory and processor power. An active service worker is automatically restarted to respond to events, such as {{domxref("ServiceWorkerGlobalScope.fetch_event", "fetch")}} or {{domxref("ServiceWorkerGlobalScope.message_event", "message")}}.
Additionally, synchronous requests are not allowed from within a service worker — only asynchronous requests, like those initiated via the {{domxref("WorkerGlobalScope/fetch", "fetch()")}} method, can be used.
This interface inherits from the {{domxref("WorkerGlobalScope")}} interface, and its parent {{domxref("EventTarget")}}.
{{InheritanceDiagram}}
This interface inherits properties from the {{domxref("WorkerGlobalScope")}} interface, and its parent {{domxref("EventTarget")}}.
This interface inherits methods from the {{domxref("WorkerGlobalScope")}} interface, and its parent {{domxref("EventTarget")}}.
Listen to this event using {{domxref("EventTarget/addEventListener()", "addEventListener()")}} or by assigning an event listener to the oneventname property of this interface.
This code snippet is from the service worker prefetch sample (see prefetch example live.) The {{domxref("ServiceWorkerGlobalScope.fetch_event", "onfetch")}} event handler listens for the fetch event. When fired, the code returns a promise that resolves to the first matching request in the {{domxref("Cache")}} object. If no match is found, the code fetches a response from the network.
The code also handles exceptions thrown from the {{domxref("WorkerGlobalScope/fetch", "fetch()")}} operation. Note that an HTTP error response (e.g., 404) will not trigger an exception. It will return a normal response object that has the appropriate error code set.
self.addEventListener("fetch", (event) => {
console.log("Handling fetch event for", event.request.url);
event.respondWith(
caches.match(event.request).then((response) => {
if (response) {
console.log("Found response in cache:", response);
return response;
}
console.log("No response found in cache. About to fetch from network…");
return fetch(event.request).then(
(response) => {
console.log("Response from network is:", response);
return response;
},
(error) => {
console.error("Fetching failed:", error);
throw error;
},
);
}),
);
});
{{Specifications}}
{{Compat}}