-
-
Save getify/7d4e6dc313bcfaa0b8ad040225114eef to your computer and use it in GitHub Desktop.
periodic sync example code
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
// .. | |
self.addEventListener("periodicsync",onPeriodicSync); | |
// .. | |
await registerPeriodicSync(); | |
// .. | |
async function registerPeriodicSync() { | |
try { | |
// periodic sync supported? | |
if ("periodicSync" in self.registration) { | |
let status = await navigator.permissions.query({ | |
name: "periodic-background-sync", | |
}); | |
// periodic sync allowed? | |
if (status.state == "granted") { | |
let tags = await self.registration.periodicSync.getTags(); | |
// daily sync hasn't been registered yet? | |
if (!tags.includes("daily-sync")) { | |
await self.registration.periodicSync.register("daily-sync",{ | |
// periodic update-check once per day | |
minInterval: 24 * 60 * 60 * 1000, | |
}); | |
console.log("sync event registered!"); | |
} | |
} | |
} | |
} | |
catch (err) {} | |
} | |
function onPeriodicSync(event) { | |
if (event.tag == "daily-sync") { | |
console.log(`periodic-sync-event: ${event.tag}`); | |
event.waitUntil(Promise.all([ | |
// check the service-worker on the server to see | |
// if it's been updated | |
self.registration.update(), | |
( | |
// show the app-icon badge (daily reminder)? | |
navigator.setAppBadge ? | |
navigator.setAppBadge() : | |
undefined | |
), | |
// temporary periodic-sync event logging (on the server) | |
router(new Request("/pse")), | |
])); | |
} | |
} | |
// .. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks for sharing! Kyle
For future readers; this https://developer.mozilla.org/en-US/docs/Web/API/Web_Periodic_Background_Synchronization_API (MDN article) should be a great place to explore more.