add service worker for offline access

This commit is contained in:
Ondrej Synacek 2019-10-20 20:32:25 +02:00
parent 132c6a2807
commit 88ae765672
3 changed files with 69 additions and 1 deletions

View File

@ -14,6 +14,7 @@ const app = express()
app.set('view engine', 'ejs')
app.set('views', path.join(__dirname, 'views'))
app.use(express.static(path.join(__dirname, 'public')))
app.use(favicon(path.join(__dirname, 'views', 'favicon.ico')))
app.use(bodyParser())

View File

@ -0,0 +1,19 @@
self.addEventListener('install', (event) => {
event.waitUntil(
caches.open('fb-to-ical').then((cache) => {
return cache.addAll([
'/',
'/favicon.ico',
])
})
)
})
self.addEventListener('fetch', (event) => {
event.respondWith(
caches.match(event.request)
.then((response) => {
return response || fetch(event.request)
})
)
})

View File

@ -72,6 +72,8 @@
</div>
<div class="status-item" id="error">
</div>
<div class="status-item" id="service-worker">
</div>
</div>
</div>
@ -112,6 +114,10 @@
}
const getStorage = () => {
if (!useStorage) {
return null
}
const storage = localStorage.getItem('fb-to-ical-events')
if (!storage) {
@ -249,6 +255,13 @@
error.classList.add('show')
}
const setServiceWorkerStatus = (status) => {
clearStatuses()
const sw = document.querySelector('#service-worker')
sw.innerText = status
status ? sw.classList.add('show') : sw.classList.remove('show')
}
const pendingRequest = () => {
input.disabled = true
submitButton.disabled = true
@ -292,8 +305,43 @@
const link = document.querySelector("#current-download")
const table = document.querySelector('#list')
const tableBody = table.querySelector('tbody')
const noJScheckbox = document.querySelector('#nojs')
hydrateList()
const loadNoJS = () => {
if (!useStorage) {
return
}
const value = localStorage.getItem('fb-to-ical-nojs')
noJScheckbox.checked = value ? JSON.parse(value) : false
}
loadNoJS()
if (window.navigator && window.navigator.serviceWorker && !noJS()) {
const serviceWorker = window.navigator.serviceWorker
serviceWorker.register('service-worker.js', {
scope: './',
}).then((registration) => {
setServiceWorkerStatus(`Service worker registered with scope ${registration.scope}`)
setTimeout(() => {
setServiceWorkerStatus('')
}, 4500)
}).catch((err) => {
setServiceWorkerStatus(`Service worker error: ${err.toString()}`)
})
}
if (!noJS()) {
hydrateList()
}
noJScheckbox.addEventListener('click', (event) => {
if (!useStorage) {
return
}
localStorage.setItem('fb-to-ical-nojs', event.target.checked)
})
submitButton.addEventListener('click', (event) => {
if (noJS()) {