Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Switch to the tab that sent the notification when the notification is clicked?

Let's say I have a site and it sends a notification in the background while the tab is still open. How do I have the browser switch to my tab if the user clicks on my notification using JavaScript (pure, no jQuery)?

like image 518
Joshua Herron Avatar asked Sep 02 '25 06:09

Joshua Herron


1 Answers

I'm assuming you are using the Notifications API. In your code, after you create the notification, you'll want to add an onclick event and tell it to focus on the tab (rather than the browser).

let notification = new Notification('Test Notification'});
notification.onclick = function () { 
    window.parent.parent.focus();
};

According to the documentation, you can also use the addEventListener() method instead of onclick if you like.

like image 133
amflare Avatar answered Sep 04 '25 21:09

amflare



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!