Brak opisu
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

ordine-notifica.js 3.0KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114
  1. import { initializeApp } from 'firebase/app';
  2. import { getMessaging, getToken, isSupported, onMessage } from 'firebase/messaging';
  3. const app = initializeApp(window.firebaseConfig);
  4. let messaging = null;
  5. let onMessageRegistered = false;
  6. async function getMessagingInstance() {
  7. if (messaging) {
  8. return messaging;
  9. }
  10. if (!window.isSecureContext) {
  11. throw new Error(
  12. 'Le notifiche richiedono HTTPS (o localhost). Apri il sito con https:// o http://fest.test sullo stesso PC.'
  13. );
  14. }
  15. const supported = await isSupported();
  16. if (!supported) {
  17. throw new Error('Il browser non supporta le notifiche push.');
  18. }
  19. messaging = getMessaging(app);
  20. return messaging;
  21. }
  22. async function chiediTokenFcm() {
  23. if (!window.isSecureContext) {
  24. throw new Error(
  25. 'Le notifiche richiedono HTTPS (o localhost). Apri il sito con https:// o http://fest.test sullo stesso PC.'
  26. );
  27. }
  28. const supported = await isSupported();
  29. if (!supported) {
  30. throw new Error('Il browser non supporta le notifiche push.');
  31. }
  32. const permesso = await Notification.requestPermission();
  33. if (permesso !== 'granted') {
  34. throw new Error('Permesso notifiche negato');
  35. }
  36. // 1. Registra il Service Worker
  37. const registration = await navigator.serviceWorker.register('/firebase-messaging-sw.js');
  38. // 2. Aspetta che sia attivo (fix "no active Service Worker")
  39. await navigator.serviceWorker.ready;
  40. // 3. Solo ora inizializza messaging
  41. const msg = await getMessagingInstance();
  42. const token = await getToken(msg, {
  43. vapidKey: window.firebaseVapidKey,
  44. serviceWorkerRegistration: registration,
  45. });
  46. if (!token) {
  47. throw new Error('Token FCM non ottenuto');
  48. }
  49. if (!onMessageRegistered) {
  50. onMessage(msg, (payload) => {
  51. const title = payload.notification?.title ?? 'Ordine pronto';
  52. const body = payload.notification?.body ?? '';
  53. new Notification(title, { body });
  54. });
  55. onMessageRegistered = true;
  56. }
  57. return token;
  58. }
  59. const btn = document.getElementById('btn-notificami');
  60. btn?.addEventListener('click', async () => {
  61. try {
  62. btn.disabled = true;
  63. const fcmToken = await chiediTokenFcm();
  64. const ordineId = btn.dataset.ordineId;
  65. if (!ordineId) {
  66. throw new Error('ID ordine non trovato nella pagina');
  67. }
  68. const body = new FormData();
  69. body.append('fcm_token', fcmToken);
  70. body.append('ordine_id', ordineId);
  71. const res = await fetch(window.subscribeUrl, {
  72. method: 'POST',
  73. headers: {
  74. 'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content,
  75. Accept: 'application/json',
  76. },
  77. body,
  78. });
  79. const data = await res.json().catch(() => ({}));
  80. if (!res.ok || data.success === false || data.res === false) {
  81. throw new Error(data.message || 'Errore salvataggio token');
  82. }
  83. document.getElementById('msg-successo')?.classList.remove('d-none');
  84. } catch (err) {
  85. alert(err.message || 'Impossibile attivare le notifiche');
  86. btn.disabled = false;
  87. }
  88. });