keanu-weblite/src/plugins/notificationAndServiceWorker.js

71 lines
2.1 KiB
JavaScript
Raw Normal View History

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.');
}
}
2023-10-01 14:31:00 +03:00
export function registerServiceWorker() {
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);
}
});
2023-10-01 22:38:11 +03:00
} else {
console.log("No Service Worker support!");
}
2023-10-01 14:31:00 +03:00
}
export async function requestNotificationPermission() {
2023-10-01 22:38:11 +03:00
if("PushManager" in window) {
return Notification?.requestPermission().then((permission) => permission);
2023-10-01 22:38:11 +03:00
} else {
console.log("No Push API Support!");
}
}
export function windowNotificationPermission() {
return window?.Notification?.permission ?? 'Not_supported'
}
export function notificationCount() {
return this.$matrix.notificationCount
}