v1.0.0
This commit is contained in:
104
web/lib/components/webPush.js
Normal file
104
web/lib/components/webPush.js
Normal file
@@ -0,0 +1,104 @@
|
||||
|
||||
const webPush = {
|
||||
async init() {
|
||||
if (!('serviceWorker' in navigator) || !('PushManager' in window)) {
|
||||
console.error('Push уведомления не поддерживаются');
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
// Получаем публичный ключ VAPID с сервера
|
||||
const uuid = localStorage.getItem('uuid');
|
||||
const res = await fetch(`${CONFIG.api}push/key`, {
|
||||
method: 'GET',
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
"Authorization": uuid
|
||||
}
|
||||
});
|
||||
const { publicKey } = await res.json();
|
||||
|
||||
// Преобразуем ключ
|
||||
function urlBase64ToUint8Array(base64String) {
|
||||
const padding = '='.repeat((4 - (base64String.length % 4)) % 4);
|
||||
const base64 = (base64String + padding).replace(/-/g, '+').replace(/_/g, '/');
|
||||
const raw = atob(base64);
|
||||
return Uint8Array.from([...raw].map(ch => ch.charCodeAt(0)));
|
||||
}
|
||||
|
||||
// Берем уже зарегистрированный Service Worker
|
||||
const registration = await navigator.serviceWorker.ready;
|
||||
|
||||
// Проверяем, есть ли уже подписка
|
||||
let subscription = await registration.pushManager.getSubscription();
|
||||
|
||||
if (!subscription) {
|
||||
|
||||
// Запрашиваем разрешение
|
||||
const permission = await Notification.requestPermission();
|
||||
if (permission !== 'granted') {
|
||||
console.warn('Пуш уведомления запрещены пользователем');
|
||||
return;
|
||||
}
|
||||
|
||||
// Подписка на push
|
||||
subscription = await registration.pushManager.subscribe({
|
||||
userVisibleOnly: true,
|
||||
applicationServerKey: urlBase64ToUint8Array(publicKey)
|
||||
});
|
||||
|
||||
// данные устройства
|
||||
const deviceInfo = {
|
||||
name: navigator.userAgent,
|
||||
model: navigator.platform || "unknown"
|
||||
};
|
||||
|
||||
// Отправка на сервер
|
||||
await fetch(`${CONFIG.api}push/subscribe`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
"Authorization": uuid
|
||||
},
|
||||
body: JSON.stringify({ subscription, device: deviceInfo })
|
||||
});
|
||||
|
||||
console.log('Push подписка готова:', subscription);
|
||||
|
||||
console.log('Создана новая подписка');
|
||||
} else {
|
||||
console.log('Подписка уже существует');
|
||||
}
|
||||
|
||||
} catch (err) {
|
||||
console.error('Ошибка инициализации push:', err);
|
||||
}
|
||||
},
|
||||
|
||||
async unsubscribe() {
|
||||
const uuid = localStorage.getItem('uuid');
|
||||
const registration = await navigator.serviceWorker.ready;
|
||||
const subscription = await registration.pushManager.getSubscription();
|
||||
|
||||
if (subscription) {
|
||||
// удаляем подписку в браузере
|
||||
const success = await subscription.unsubscribe();
|
||||
|
||||
if (success) {
|
||||
console.log("Локальная подписка отменена");
|
||||
|
||||
// уведомляем сервер
|
||||
await fetch(`${CONFIG.api}push//unsubscribe`, {
|
||||
method: "DELETE",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
"Authorization": uuid
|
||||
},
|
||||
body: JSON.stringify({ endpoint: subscription.endpoint })
|
||||
});
|
||||
}
|
||||
} else {
|
||||
console.log("Подписки нет");
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user