POC: Mobile notification via periodicSync

This commit is contained in:
10G Meow 2023-11-26 13:51:15 +02:00
parent b14749c28f
commit 2aa97cf134
3 changed files with 78 additions and 6 deletions

View file

@ -1,6 +1,53 @@
import { isMobileOrTabletBrowser } from './utils'
const registerPeriodicBackgroundSync = async (registration) => {
// Check if periodicSync is supported
if ('periodicSync' in registration) {
// Request permission
const status = await navigator.permissions.query({
name: 'periodic-background-sync',
});
if (status.state === 'granted') {
console.log('PBS registered and granted')
try {
// Register the periodic background sync.
await registration.periodicSync.register('check-new-messages', {
// minInterval is one day
minInterval: 24 * 60 * 60 * 1000,
});
console.log('Periodic background sync registered!');
console.log(registration.periodicSync.getTags())
// List registered periodic background sync tags.
const tags = await registration.periodicSync.getTags();
if (tags.length) {
tags.forEach((tag) => {
console.log('tag')
console.log(tag)
});
}
} catch(e) {
console.log(`Periodic background sync failed: ${e}`);
}
} else {
console.log('Periodic background sync is not granted.');
}
} else {
console.log('Periodic background sync is not supported.');
}
}
export function registerServiceWorker() {
if("serviceWorker" in navigator) {
navigator.serviceWorker.register("/sw.js");
if ('serviceWorker' in navigator) {
window.addEventListener('load', async () => {
const registration = await navigator.serviceWorker.register("/sw.js");
console.log('Service worker registered for scope', registration.scope);
if(isMobileOrTabletBrowser) {
await registerPeriodicBackgroundSync(registration);
}
});
} else {
console.log("No Service Worker support!");
}