-
Notifications
You must be signed in to change notification settings - Fork 2
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
6ba8921
commit bdf4960
Showing
1 changed file
with
57 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,57 @@ | ||
// This is the "Offline page" service worker | ||
|
||
const CACHE = "pwabuilder-page"; | ||
|
||
// TODO: replace the following with the correct offline fallback page i.e.: const offlineFallbackPage = "offline.html"; | ||
const offlineFallbackPage = "ToDo-replace-this-name.html"; | ||
|
||
// Install stage sets up the offline page in the cache and opens a new cache | ||
self.addEventListener("install", function (event) { | ||
console.log("[PWA Builder] Install Event processing"); | ||
|
||
event.waitUntil( | ||
caches.open(CACHE).then(function (cache) { | ||
console.log("[PWA Builder] Cached offline page during install"); | ||
|
||
if (offlineFallbackPage === "ToDo-replace-this-name.html") { | ||
return cache.add(new Response("TODO: Update the value of the offlineFallbackPage constant in the serviceworker.")); | ||
} | ||
|
||
return cache.add(offlineFallbackPage); | ||
}) | ||
); | ||
}); | ||
|
||
// If any fetch fails, it will show the offline page. | ||
self.addEventListener("fetch", function (event) { | ||
if (event.request.method !== "GET") return; | ||
|
||
event.respondWith( | ||
fetch(event.request).catch(function (error) { | ||
// The following validates that the request was for a navigation to a new document | ||
if ( | ||
event.request.destination !== "document" || | ||
event.request.mode !== "navigate" | ||
) { | ||
return; | ||
} | ||
|
||
console.error("[PWA Builder] Network request Failed. Serving offline page " + error); | ||
return caches.open(CACHE).then(function (cache) { | ||
return cache.match(offlineFallbackPage); | ||
}); | ||
}) | ||
); | ||
}); | ||
|
||
// This is an event that can be fired from your page to tell the SW to update the offline page | ||
self.addEventListener("refreshOffline", function () { | ||
const offlinePageRequest = new Request(offlineFallbackPage); | ||
|
||
return fetch(offlineFallbackPage).then(function (response) { | ||
return caches.open(CACHE).then(function (cache) { | ||
console.log("[PWA Builder] Offline page updated from refreshOffline event: " + response.url); | ||
return cache.put(offlinePageRequest, response); | ||
}); | ||
}); | ||
}); |