Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to auto focus browser tab when clicking on browser notification in Chrome?

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

like image 413
Marko Avatar asked Aug 11 '15 18:08

Marko


1 Answers

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();
      }
    })
  );
});
like image 142
Marco Castelluccio Avatar answered Oct 22 '22 21:10

Marco Castelluccio