1

I'm using a growl-like plugin for jQuery send live messages to users to share activity on the site. Right now I only update the user with notifications that happened since the user's last access on the site. However, when I have multiple tabs open on the site, only some of the tabs get the notifications due to the long polling requests as a tab can flush the notification before the other tabs get them.

What is the best way to implement a notification system where each tab will display the messages at the same time? Perhaps also to maintain a level of persistence so that, say, the notifications will stay on the page for 15 seconds even if a user navigations to a different page?

Thank you.

ensnare
  • 34,050
  • 49
  • 140
  • 211

1 Answers1

0

You can use window.localStorage object as a buffer for notifications that is shared between tabs/windows. To ensure cross-browser compatibility you can also use store.js library instead of dealing with localStorage directly.

So you can send your notifications to client via web-socket or in any other way and the handler will push them to this buffer. Say this would be an array like

[
    notification1,
    notification2
    // etc.
]

Each window (tab) should be registered in localStorage when user opens it, like:

{
    wnd_<timestamp_of_window1_onload_event>: 1
    wnd_<timestamp_of_window2_onload_event>: 1
}

In each window (tab) you can use a window.setInterval function to check the buffer every N milliseconds for a new notifications. The function called by setInterval will read new notifications from buffer and display them. In window.onbeforeunload handler you'll unregister current window from windows collection in localStorage. And if the collection of windows became empty after current window unregistering, you can empty the buffer of notifications. Sure, It's a brief solution, maybe you'll need to think about the deleting of deprecated (handled by all windows) notifications from buffer before all windows closing.

Eugene Naydenov
  • 6,711
  • 1
  • 20
  • 38