8. sw.js

1
const URL_SERVIDOR = "https://notipush.rf.gd"
2
3
if (self instanceof ServiceWorkerGlobalScope) {
4
5
 // El siguiente código se activa cuando llega una notificación push.
6
 self.addEventListener("push", (/** @type {PushEvent} */ event) => {
7
  const notificacion = event.data
8
  /* Si el navegador tiene permitido mostrar notificaciones push,
9
   * nuestra la que se ha recibido. */
10
  if (notificacion !== null && self.Notification.permission === 'granted') {
11
   event.waitUntil(muestraNotificacion(notificacion))
12
  }
13
 })
14
15
 self.addEventListener("notificationclick",
16
  (/** @type {NotificationEvent} */ event) => {
17
   event.notification.close()
18
   event.waitUntil(muestraVentana())
19
  })
20
}
21
22
/**
23
 * @param {PushMessageData} notificacion
24
 */
25
async function muestraNotificacion(notificacion) {
26
 if (self instanceof ServiceWorkerGlobalScope) {
27
  const mensaje = notificacion.text()
28
  await self.registration.showNotification(mensaje)
29
 }
30
}
31
32
async function muestraVentana() {
33
 if (self instanceof ServiceWorkerGlobalScope) {
34
  const clientes = await self.clients.matchAll({ type: "window" })
35
  for (const cliente of clientes) {
36
   if (cliente.url.startsWith(URL_SERVIDOR)) {
37
    return cliente.focus()
38
   }
39
  }
40
  return self.clients.openWindow("/")
41
 }
42
}
skip_previous skip_next