linkD
linkD

Reputation: 141

JavaScript: Avoiding duplicate Notifications

When I receive a WebSocket message, I display a Notification using new Notification("Hello world!"); with the parsed data.

This works fine. The problem is, when I have multiple tabs open, I get notified multiple times - once for every tab open that has the script running.

I've thought of setting a cookie/LocalStorage, but that would run into a race condition. Another possibility might be to do the notifying in a Singleton, but since tabs are isolated from one another, there's no easy way to do that - or is there?

// This doesn't work - still getting duplicate notifications
if ($.cookie("already-notified-" + event.id) != null)
    return;

$.cookie("already-notified-" + event.id, true);
new Notification("Hello world!");

How do I make sure there are no duplicate notifications?

Upvotes: 1

Views: 2092

Answers (2)

linkD
linkD

Reputation: 141

The solution for my problem was pretty simple after all; just not quite what I had in mind. I was very focused on a client side solution though it was (in my case) a lot simpler to go with a little trick on the server side.

What I did was store the connections in a dict with the username as key and a list of the combination of IP and port as value, a little something like this:

{
  "linkD": [92.135.241.187:34214, 92.135.241.187:13245, 92.135.241.187:25313],
  "amflare": [124.81.193.73:48239, 124.81.193.73:38293],
}

Since each new WebSocket connection is handled through a different port, I can simply append any new connections to the list and only send a notification to the most recent (last in the list) WebSocket. On disconnect, the connection simply gets removed from the list.

Upvotes: 0

amflare
amflare

Reputation: 4113

So long as it's coming from the same domain you can use notification tags in the options object. It looks like this:

new Notification('Test Notification', {
  tag: 'tagname'
});

Technically, this does not prevent multiple notification, but rather replaces existing notifications. If you have several fire at the same time, it will look like a single notification, if they are staggered by several seconds, it may look like an extended notification, or like several. However, since the previous notifications are removed, they won't stack, and you will only have one notification when all is said and done.

Be careful using this since you may find that notifications stop occurring after the first set. If this happens, you'll need to add renotify: true to the option object. This occurs because the computer thinks "I have already sent a notification of domain:stackoverflow.com-tag:tagname, I don't need to send another." renotify defaults to false, so changing it to true fixes the problem.

Since you appear to be using event IDs in your code (which will change the tag), you probably won't encounter this issue, but it's good to be aware of.

Upvotes: 4

Related Questions