JenuRudan
JenuRudan

Reputation: 545

Push browser notification - on click dynamic url

I'm using push browser notifications in my project, everything is working fine except for clicking on notification, i want it to open dynamic url according to notification data

my code

self.addEventListener('push', function(event) {
  console.log('[Service Worker] Push Received.');
  console.log(`[Service Worker] Push had this data: "${event.data.text()}"`);

  const title = 'Garment IO';

  const options = {
    body: getAlertData(event.data.text()),
    icon: '../images/icon.png',
    dir:'rtl',
    badge: '../images/badge.png'
  };
  event.waitUntil(self.registration.showNotification(title, options));
});

self.addEventListener('notificationclick', function(event) {
  console.log('[Service Worker] Notification click Received.');

  event.notification.close();

  event.waitUntil(
    clients.openWindow('https://google.com');///want to change this !
  );
});

so is there any attribute i can push in event ? like url or sth ?

Upvotes: 1

Views: 2867

Answers (2)

Willy Rosa Huanca
Willy Rosa Huanca

Reputation: 45

There is a mistake in the above answer, because url does not exist in data, as he said you have to pass a json string with JSON.stringify() and then convert it back to json with data.json(), so this my final correct code.

self.addEventListener('push', function(event) {
    console.log('[Service Worker] Push Received.');
    console.log(`[Service Worker] Push had this data: "${event.data.json()}"`);

    const myObject = event.data.json();
    //const title = 'Nueva Reserva Alpaca Expeditions';
    const options = {
      body: myObject.bodyText,
      data: myObject.url,
      icon: '/assets/icon.png',
      badge: '/assets/badge.png'
    };

    const notificationPromise = self.registration.showNotification(myObject.title, options);
    event.waitUntil(notificationPromise);
  });

self.addEventListener('notificationclick', function(event) {
  console.log('[Service Worker] Notification click Received.');
  console.info(event.notification)
  event.notification.close();

  event.waitUntil(
    clients.openWindow(event.notification.data)
  );
});

Upvotes: 1

Stef Chäser
Stef Chäser

Reputation: 2058

Instead of passing only text into the push handler you can pass in a stringified object (with JSON.stringify()), which you parse back into a object with event.data.json(). Then you can set the url as part of the data property of the notification object.

self.addEventListener('push', function(event) {
  const myObject = event.data.json();
  const options = {
    body: myObject.bodyText,
    data: myObject.url,
    ...
  };
  return self.registration.showNotification(myObject.title, options);
});

The data object is later accessible in the "notificationclick" event

self.addEventListener("notificationclick", function(event) {
  event.waitUntil(clients.openWindow(event.notification.data.url));    
});

Upvotes: 3

Related Questions