Skip to content

Instantly share code, notes, and snippets.

@PonomareVlad
Last active November 3, 2022 14:38
Show Gist options
  • Save PonomareVlad/ccc3d1725d29052220b9b92605802153 to your computer and use it in GitHub Desktop.
Save PonomareVlad/ccc3d1725d29052220b9b92605802153 to your computer and use it in GitHub Desktop.
if (typeof navigator.serviceWorker !== 'undefined')
navigator.serviceWorker.register('/sw.js');
let deferredPrompt;
const addBtn = document.querySelector("#install-button");
window.addEventListener("beforeinstallprompt", (e) => {
e.preventDefault();
deferredPrompt = e;
addBtn.addEventListener("click", (e) => {
deferredPrompt.prompt();
deferredPrompt.userChoice.then((choiceResult) => {
if (choiceResult.outcome === "accepted") {
console.log("User accepted the A2HS prompt");
} else {
console.log("User dismissed the A2HS prompt");
}
deferredPrompt = null;
});
});
});
// This is the "Offline page" service worker
importScripts('https://storage.googleapis.com/workbox-cdn/releases/5.1.2/workbox-sw.js');
const CACHE = "pwabuilder-page";
// TODO: replace the following with the correct offline fallback page i.e.: const offlineFallbackPage = "offline.html";
const offlineFallbackPage = "/index.html";
self.addEventListener("message", (event) => {
if (event.data && event.data.type === "SKIP_WAITING") {
self.skipWaiting();
}
});
self.addEventListener('install', async (event) => {
event.waitUntil(
caches.open(CACHE)
.then((cache) => cache.add(offlineFallbackPage))
);
});
if (workbox.navigationPreload.isSupported()) {
workbox.navigationPreload.enable();
}
self.addEventListener('fetch', (event) => {
if (event.request.mode === 'navigate') {
event.respondWith((async () => {
try {
const preloadResp = await event.preloadResponse;
if (preloadResp) {
return preloadResp;
}
const networkResp = await fetch(event.request);
return networkResp;
} catch (error) {
const cache = await caches.open(CACHE);
const cachedResp = await cache.match(offlineFallbackPage);
return cachedResp;
}
})());
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment