herronjo
herronjo

Reputation: 95

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)?

Upvotes: 3

Views: 1828

Answers (1)

amflare
amflare

Reputation: 4113

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.

Upvotes: 10

Related Questions