Add a notification badge to show unread messages
You can notify users about new messages even when they’re not viewing the chat, by adding a notification badge to your app’s header. A common example is an icon with a red badge showing the number of unread conversations, similar to LinkedIn’s message icon:
You can add a badge with the number of unread conversations using the Unreads object, which provides event handlers for incoming messages.
For example, assuming you're using JQuery and your notifier badge is an HTML element with id="notifier-badge"
, you could append this code to the function body:
1session.unreads.onChange(function (unreadConversations) {2 const amountOfUnreads = unreadConversations.length;34 // Update the badge text and control visibility5 $('#notifier-badge')6 .text(amountOfUnreads)7 .toggle(amountOfUnreads > 0);89 // Update the tab title to show unread counts10 if (amountOfUnreads > 0) {11 document.title = '(' + amountOfUnreads + ') MySite';12 } else {13 document.title = 'MySite';14 }15});
The onChange
event is called whenever the number of unread conversations changes, and also on startup. You can find a complete example on our examples repository on GitHub.
See the Session JavaScript API reference for additional events and features.
Users must allow browser notifications before TalkJS can display them. TalkJS automatically triggers the permission dialog the first time notifications are enabled, or when the user toggles browser notifications on.
You can customize this flow by listening to the onBrowserPermissionNeeded and onBrowserPermissionDenied events to show your own dialogs or help messages.
Once browser permissions are granted, TalkJS can display desktop notifications for new messages when your app is open in a browser tab.