Skip to content

Instantly share code, notes, and snippets.

@webmaxru
Last active November 29, 2018 16:52
Show Gist options
  • Save webmaxru/d4a1fc609026831062fce707aa34e88c to your computer and use it in GitHub Desktop.
Save webmaxru/d4a1fc609026831062fce707aa34e88c to your computer and use it in GitHub Desktop.
Background Fetch. Step 2: Storing the data received
<script>
bgFetchButton.addEventListener('click', async event => {
try {
event.target.disabled = true;
const registration = await navigator.serviceWorker.ready;
registration.backgroundFetch.fetch('my-fetch', [
'/assets/s01e01.mpg',
'/assets/s01e02.mpg'
]);
} catch (err) {
alert(
'Please enable downloads for this website (click the icon on the right side of the address bar)'
);
console.error(err);
}
});
</script>
addEventListener('backgroundfetchsuccess', event => {
console.log('[Service Worker]: Background Fetch Success', 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;
await cache.put(record.request, response);
});
await Promise.all(promises);
} catch (err) {
console.error(err)
}
})()
);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment