Created
February 11, 2021 08:55
-
-
Save galulex/9a97a5d116d919174d1c8be8564c0286 to your computer and use it in GitHub Desktop.
ServiceWorker.js
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
// This is the "Offline page" service worker | |
importScripts('https://storage.googleapis.com/workbox-cdn/releases/5.0.0/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 = "offline.html"; | |
self.addEventListener("message", (event) => { | |
if (event.data && event.data.type === "SKIP_WAITING") { | |
self.skipWaiting(); | |
} | |
if (event.data && event.data.type === 'notify') notify() | |
console.log(event) | |
}); | |
if (workbox.navigationPreload.isSupported()) { | |
workbox.navigationPreload.enable(); | |
} | |
function notify(body = " ", actions = [{action: 'home', title: 'Home'}, {action: 'garage', title: 'Garage'}, {action: 'backgates', title: 'Backgates'}]) { | |
self.registration.showNotification('', { | |
badge: 'https://i.imgur.com/9QFB20F.png', | |
icon: 'data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7', | |
body: body, | |
actions: actions, | |
tag: 'notification', | |
silent: true, | |
requireInteraction: true | |
}) | |
} | |
async function xhr(action, actions = {home: '380635312251', garage: '380634828442', backgates: '380634828442'}) { | |
return await fetch('https://gates.pwt.workers.dev/?phone=' + actions[action]) | |
} | |
self.addEventListener('install', async (event) => { | |
event.waitUntil( | |
caches.open(CACHE) | |
.then((cache) => cache.add(offlineFallbackPage)) | |
); | |
}); | |
self.onnotificationclick = async function(event) { | |
console.log('On notification click: ', event); | |
if (event.action === '') return notify(); | |
notify('🔄 Opening...') | |
res = await xhr(event.action) | |
res.ok ? notify('✔️ Success') : notify('❌ Failed') | |
setTimeout(notify, 2000) | |
}; | |
self.onnotificationclose = function(event) { | |
notify() | |
console.log('On notification close: ', self); | |
}; | |
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