import { initializeApp } from 'firebase/app'; import { getMessaging, getToken, isSupported, onMessage } from 'firebase/messaging'; const app = initializeApp(window.firebaseConfig); let messaging = null; let onMessageRegistered = false; async function getMessagingInstance() { if (messaging) { return messaging; } if (!window.isSecureContext) { throw new Error( 'Le notifiche richiedono HTTPS (o localhost). Apri il sito con https:// o http://fest.test sullo stesso PC.' ); } const supported = await isSupported(); if (!supported) { throw new Error('Il browser non supporta le notifiche push.'); } messaging = getMessaging(app); return messaging; } async function chiediTokenFcm() { if (!window.isSecureContext) { throw new Error( 'Le notifiche richiedono HTTPS (o localhost). Apri il sito con https:// o http://fest.test sullo stesso PC.' ); } const supported = await isSupported(); if (!supported) { throw new Error('Il browser non supporta le notifiche push.'); } const permesso = await Notification.requestPermission(); if (permesso !== 'granted') { throw new Error('Permesso notifiche negato'); } // 1. Registra il Service Worker const registration = await navigator.serviceWorker.register('/firebase-messaging-sw.js'); // 2. Aspetta che sia attivo (fix "no active Service Worker") await navigator.serviceWorker.ready; // 3. Solo ora inizializza messaging const msg = await getMessagingInstance(); const token = await getToken(msg, { vapidKey: window.firebaseVapidKey, serviceWorkerRegistration: registration, }); if (!token) { throw new Error('Token FCM non ottenuto'); } if (!onMessageRegistered) { onMessage(msg, (payload) => { const title = payload.notification?.title ?? 'Ordine pronto'; const body = payload.notification?.body ?? ''; new Notification(title, { body }); }); onMessageRegistered = true; } return token; } const btn = document.getElementById('btn-notificami'); btn?.addEventListener('click', async () => { try { btn.disabled = true; const fcmToken = await chiediTokenFcm(); const ordineId = btn.dataset.ordineId; if (!ordineId) { throw new Error('ID ordine non trovato nella pagina'); } const body = new FormData(); body.append('fcm_token', fcmToken); body.append('ordine_id', ordineId); const res = await fetch(window.subscribeUrl, { method: 'POST', headers: { 'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content, Accept: 'application/json', }, body, }); const data = await res.json().catch(() => ({})); if (!res.ok || data.success === false || data.res === false) { throw new Error(data.message || 'Errore salvataggio token'); } document.getElementById('msg-successo')?.classList.remove('d-none'); } catch (err) { alert(err.message || 'Impossibile attivare le notifiche'); btn.disabled = false; } });