1. js / lib / activaNotificacionesPush.js

1
/**
2
 * @param { string | URL } urlDeServiceWorkerQueRecibeNotificaciones
3
 */
4
export async function activaNotificacionesPush(
5
6
 urlDeServiceWorkerQueRecibeNotificaciones) {
7
8
 // Valida que el navegador soporte notificaciones push.
9
 if (!('PushManager' in window))
10
  throw new Error("Este navegador no soporta notificaciones push.")
11
12
 // Valida que el navegador soporte notificaciones,
13
 if (!("Notification" in window))
14
  throw new Error("Este navegador no soporta notificaciones push.")
15
16
 // Valida que el navegador soporte service workers,
17
 if (!("serviceWorker" in navigator))
18
  throw new Error("Este navegador no soporta service workers.")
19
20
 // Recupera el permiso para usar notificaciones
21
 let permiso = Notification.permission
22
 if (permiso === "default") {
23
  // Permiso no asignado. Pide al usuario su autorización.
24
  permiso = await Notification.requestPermission()
25
 }
26
27
 // Valida que el usuario haya permitido usar notificaciones..
28
 if (permiso === "denied")
29
  throw new Error("Notificaciones bloqueadas.")
30
31
 const registro = await navigator.serviceWorker.register(
32
  urlDeServiceWorkerQueRecibeNotificaciones)
33
 console.log(urlDeServiceWorkerQueRecibeNotificaciones, "registrado.")
34
 console.log(registro)
35
36
 if (!("showNotification" in registro))
37
  throw new Error("Este navegador no soporta notificaciones.")
38
}
skip_previous skip_next