Last active
November 29, 2018 20:53
-
-
Save webmaxru/6c3817fb19c64390ba50287a29711efc to your computer and use it in GitHub Desktop.
Background Fetch. Step 4: Extra useful handlers
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
addEventListener('backgroundfetchfail', event => { | |
console.log('[Service Worker]: Background Fetch Fail', event.registration); | |
event.waitUntil( | |
(async function() { | |
try { | |
const cache = await caches.open(event.registration.id); | |
const records = await event.registration.matchAll(); | |
const promises = records.map(async record => { | |
const response = await record.responseReady | |
if (response && response.ok) { | |
await cache.put(record.request, response); | |
} | |
}); | |
await Promise.all(promises); | |
} finally { | |
// [Optional] This could be an API call to our backend | |
let assetsDataResponse = await fetch( | |
`/assets/${event.registration.id}-data.json` | |
); | |
let assetsData = await assetsDataResponse.json(); | |
// Updating UI | |
await event.updateUI({ | |
title: `${assetsData.title} failed: ${ | |
event.registration.failureReason | |
}` | |
}); | |
} | |
})() | |
); | |
}); | |
addEventListener('backgroundfetchabort', event => { | |
console.log('[Service Worker]: Background Fetch Abort', event.registration); | |
console.error('Aborted by the user. No data was saved.'); | |
}); | |
addEventListener('backgroundfetchclick', event => { | |
console.log('[Service Worker]: Background Fetch Click', event.registration); | |
event.waitUntil( | |
(async function() { | |
let assetsDataResponse = await fetch( | |
`/assets/${event.registration.id}-data.json` | |
); | |
let assetsData = await assetsDataResponse.json(); | |
clients.openWindow(assetsData.descriptionUrl); | |
})() | |
); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment