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
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();
}
})
);
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With