test web push
Main daploy / deploy (push) Successful in 45s

This commit is contained in:
2024-11-21 16:11:23 +02:00
parent 14e8a349e6
commit 75be87c144
14 changed files with 438 additions and 63 deletions
@@ -0,0 +1,100 @@
<template>
<CreateMessageDeliveryOption :label :method v-model="model" @change="handleSelection()" />
<!-- Ошибка разрешений -->
<p v-if="permissionError && model === method" class="text-red-500 mb-2">
Не удалось получить разрешение на отправку уведомлений.<br />
<button @click="retryPushSubscription" class="text-blue-500 underline">Повторить</button>
</p>
</template>
<script setup lang="ts">
import { type QRCodeDocument } from '@/types/DBDocumentTypes'
import { type DeliveryOption, DELIVERY_METHOD_WEB_PUSH } from '@/constants/deliveryOptions'
import { ref } from 'vue'
type DeliveryOptionWebPush = Extract<DeliveryOption, { method: typeof DELIVERY_METHOD_WEB_PUSH }>
defineProps<{
label: DeliveryOptionWebPush['label']
method: DeliveryOptionWebPush['method']
}>()
const emit = defineEmits<{
(e: 'change'): void
}>()
const model = defineModel<null | QRCodeDocument['messageDeliveryMethod']>()
// Локальное состояние для уведомлений и ошибок
const permissionError = ref(false)
// Обработчик выбора
async function handleSelection() {
permissionError.value = false
const permission = await requestNotificationPermission()
if (permission) {
emit('change')
} else {
permissionError.value = true
}
}
// Функция запроса разрешений и подписки
async function requestNotificationPermission(): Promise<boolean> {
if (!('Notification' in window)) {
console.error('Уведомления не поддерживаются этим браузером.')
return false
}
try {
const permission = await Notification.requestPermission()
if (permission !== 'granted') {
console.error('Разрешение на уведомления не предоставлено.')
return false
}
const registration = await navigator.serviceWorker.ready
const subscription = await registration.pushManager.subscribe({
userVisibleOnly: true,
applicationServerKey:
'BMPwpR1Q24ZOFxy2T9M-I-Y6F6bucsHFVZKP8QYslgD_4hGCDv16qnZnji-ldngcZ_vBWVBwJ6OIfknVBnCxLsY',
})
console.log('Push-подписка создана:', subscription)
console.log(JSON.stringify(subscription))
// subscription = {
// endpoint:
// 'https://jmt17.google.com/fcm/send/eFYnP7qxt8A:APA91bHYGItzGpnzhXkfKzgMhAXgwcQXaLuRLqq9mt9RPS0VgGpEvVASxW8AF_fJmtSBtK-po0V3mM7fGWSN6tMCrImZqgZG14kGv0chQoghOLuWgHTUQYtQEqhd6f89eVonJdtjAlDN',
// expirationTime: null,
// keys: {
// p256dh:
// 'BAIGLAQ5cZg6e8psnK6vy_MJ1kUJbs2Tymjc38-_6zM1VQXWP2Yj-604uPMye4smHosNKmBEPRDJJOH6Wxr1MLQ',
// auth: '1k48wvT0U3pK_xaXW95Ekw',
// },
// }
// subscription = {
// endpoint:
// 'https://jmt17.google.com/fcm/send/eFYnP7qxt8A:APA91bHYGItzGpnzhXkfKzgMhAXgwcQXaLuRLqq9mt9RPS0VgGpEvVASxW8AF_fJmtSBtK-po0V3mM7fGWSN6tMCrImZqgZG14kGv0chQoghOLuWgHTUQYtQEqhd6f89eVonJdtjAlDN',
// expirationTime: null,
// keys: {
// p256dh:
// 'BAIGLAQ5cZg6e8psnK6vy_MJ1kUJbs2Tymjc38-_6zM1VQXWP2Yj-604uPMye4smHosNKmBEPRDJJOH6Wxr1MLQ',
// auth: '1k48wvT0U3pK_xaXW95Ekw',
// },
// }
// Здесь вы можете сохранить подписку на сервере
return true
} catch (err) {
console.error('Ошибка при создании Push-подписки:', err)
return false
}
}
// Повторный запрос разрешений
function retryPushSubscription() {
permissionError.value = false
handleSelection()
}
</script>