Skip to content

Instantly share code, notes, and snippets.

@getify
Last active February 17, 2023 11:55
Show Gist options
  • Save getify/7d4e6dc313bcfaa0b8ad040225114eef to your computer and use it in GitHub Desktop.
Save getify/7d4e6dc313bcfaa0b8ad040225114eef to your computer and use it in GitHub Desktop.
periodic sync example code
// ..
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")),
]));
}
}
// ..
@Pranav-yadav
Copy link

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment