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

Blazor Server(.NET8)聊天应用:如何判断标签页状态并触发通知音?

Blazor SignalR聊天应用:后台标签页通知音效实现

实现步骤

1. 添加JavaScript工具函数

在项目的wwwroot/js/site.js(或新建独立JS文件)中添加以下函数,用于获取标签页状态和播放音效:

// 播放通知音效,替换为你的音效文件路径
function playNotificationSound() {
    const audio = new Audio('/sounds/notification.mp3');
    audio.play().catch(err => console.error('音效播放失败:', err));
}

// 判断当前标签页是否处于激活状态
function isTabActive() {
    return !document.hidden;
}

2. 配置Blazor组件的JS互操作

在你的聊天组件顶部注入IJSRuntime,并添加获取标签页状态的异步方法:

@inject IJSRuntime JS

@* 组件其余内容 *@

@code {
    // 获取当前标签页是否激活
    private async Task<bool> IsTabActiveAsync()
    {
        return await JS.InvokeAsync<bool>("isTabActive");
    }

    // 其他现有代码...
}

3. 修改SignalR消息接收逻辑

更新你现有的消息处理代码,整合标签页状态判断,实现不同场景的处理逻辑:

// SignalR消息接收回调方法
private async Task OnMessageReceived(string senderId, string recieverId, string message, string msgId)
{
    if (recieverId == MyId)
    {
        bool tabIsActive = await IsTabActiveAsync();
        bool targetChatOpened = OpenedChat is not null && senderId == OpenedChat.User.Id;

        // 场景1:目标聊天窗口已打开且标签页激活,正常加载消息并标记已读
        if (targetChatOpened && tabIsActive)
        {
            var newMessage = new TalkChatMessage
            {
                SenderId = senderId,
                ReceiverId = MyId,
                Content = message,
                Timestamp = DateTime.Now
            };
            messages.Add(newMessage);
            
            await ChatService.ReadMessage(msgId);
            StateHasChanged();
            await ScrollToBottom();
        }
        // 场景2:聊天窗口未打开,或标签页在后台,触发通知音效
        else
        {
            await JS.InvokeVoidAsync("playNotificationSound");
            // 可选:在此处添加未读消息标记、桌面通知等额外逻辑
        }
    }
}

注意事项

  • 确保音效文件路径正确,建议将音频文件放在wwwroot/sounds目录下;
  • 浏览器的自动播放策略要求用户先与页面交互(如点击)才能播放音频,可在组件首次加载时提示用户完成一次交互以授权;
  • document.hidden属性兼容所有主流浏览器,无需额外兼容处理。

内容的提问来源于stack exchange,提问作者Igorus15

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.19 08:42:19