13

I am trying to setup browser notification for a project I'm working on. The code I have so far is:

// Notification permissions logic handled before...
var notification = new Notification('Title', { body: 'Message' });
notification.onclick = function (e) {
    window.focus();
    // this.cancel();
};
setTimeout(notification.close.bind(notification), 5000);

The notifications work fine with this code except for one thing. In Chrome clicking on the notification does not set the focus on the browser window. In Firefox this behavior is native out of the box and it works fine without on click handler defined above. I have looked for the solution for this for Chrome and found these:

How to get focus to the tab when a desktop notification is clicked in Firefox?

How to get focus to a Chrome tab which created desktop notification?

However the suggested accepted solutions do not work for me - the event is triggered but the focus is not set.

Does anyone have any suggestions how to make this behave properly?

Chrome version: Version 44.0.2403.130 m

Firefox version: 40.0

Community
  • 1
  • 1
Marko
  • 11,003
  • 8
  • 43
  • 55

1 Answers1

3

It's an hacky solution, but if you registered a service worker you could do something like this.

In the client page:

yourServiceWorkerRegistration.showNotification('Title', {
  body: 'Message',
});

In the service worker:

self.addEventListener('notificationclick', event => {
  event.notification.close();

  event.waitUntil(
    clients.matchAll({
      type: "window",
    })
    .then(clientList => {
      if (clientList.length) {
        clientList[0].focus();
      }
    })
  );
});
Marco Castelluccio
  • 8,715
  • 2
  • 27
  • 45