'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



Solution 1:[1]

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();
      }
    })
  );
});

Solution 2:[2]

Now, my chrome version is 100.0.4896.127. And window.focus() works perfect in onclick of notification callback! It would be helpful to anyone who sees this issue.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Marco Castelluccio
Solution 2 Taehyun Hwang