Last active
November 29, 2018 16:52
-
-
Save webmaxru/d4a1fc609026831062fce707aa34e88c to your computer and use it in GitHub Desktop.
Background Fetch. Step 2: Storing the data received
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
<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> |
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('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