You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何利用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.hidden API (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 toggleTabBlink function uses setInterval to flip between the original page title and a "New Message!" alert. When the user switches back to the tab, the visibilitychange event fires, clearing the interval and restoring the original title automatically.
  • ChatKit Integration: In the onMessage hook 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 1000 ms value in setInterval (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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.06 19:57:44