如何利用Pusher ChatKit实现消息接收时浏览器标签闪烁(含纯JS示例)
Hey there, I've put together a pure JavaScript solution that handles browser tab blinking when a ChatKit message arrives and the user isn't focused on your tab. It's straightforward and plays nicely with ChatKit's event system:
Step-by-Step Implementation
First, we need two core pieces: a way to detect if the tab is active, and a function to toggle the tab title for that blinking effect. Then we hook this into ChatKit's message received event.
Full Code Example
// Store the original tab title to revert back later const originalTitle = document.title; let blinkInterval = null; // Function to start/stop tab blinking function toggleTabBlink() { if (document.hidden) { // Start blinking if tab is not focused blinkInterval = setInterval(() => { document.title = document.title === originalTitle ? '🔔 New Message!' : originalTitle; }, 1000); } else { // Stop blinking and restore original title when tab is focused clearInterval(blinkInterval); document.title = originalTitle; blinkInterval = null; // Reset interval reference } } // Listen for tab focus changes to auto-stop blinking document.addEventListener('visibilitychange', toggleTabBlink); // Initialize ChatKit Client (replace with your own credentials) const chatManager = new Chatkit.ChatManager({ instanceLocator: 'YOUR_INSTANCE_LOCATOR', userId: 'CURRENT_USER_ID', tokenProvider: new Chatkit.TokenProvider({ url: 'YOUR_TOKEN_ENDPOINT' }) }); chatManager.connect() .then(currentUser => { console.log('Connected as user:', currentUser.id); // Subscribe to the target room to listen for messages currentUser.subscribeToRoom({ roomId: 'TARGET_ROOM_ID', hooks: { // Trigger blinking when a new message comes in onMessage: message => { // Only initiate blinking if tab is unfocused and not already blinking if (document.hidden && !blinkInterval) { toggleTabBlink(); } } } }); }) .catch(error => { console.error('Error connecting to ChatKit:', error); });
Key Details Explained
- Tab Focus Detection: We use the
document.hiddenAPI (part of the Page Visibility API) which works across all modern browsers. It instantly tells us if the current tab is in the background. - Blink Logic: The
toggleTabBlinkfunction usessetIntervalto flip between the original page title and a "New Message!" alert. When the user switches back to the tab, thevisibilitychangeevent fires, clearing the interval and restoring the original title automatically. - ChatKit Integration: In the
onMessagehook of your subscribed room, we check if the tab is hidden. If it is, we start the blinking effect (but only if it's not already running to avoid duplicate intervals).
Quick Customization Tips
- Adjust the blink speed by changing the
1000ms value insetInterval(lower = faster blink). - Swap the alert title text (
'🔔 New Message!') to match your app's tone. - Don't forget to replace all placeholder values (
YOUR_INSTANCE_LOCATOR,CURRENT_USER_ID, etc.) with your actual ChatKit credentials.
内容的提问来源于stack exchange,提问作者Adwait soni
相关产品推荐
相关产品推荐

