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

紧急天气应用故障:已接收紧急疏散警报但无法显示

问题解决:Supabase Realtime紧急警报无法显示的修复方案

问题背景

我们开发了一款集成weather.com API与Supabase Realtime的高级天气应用,用于展示紧急警报。测试时发现:日志显示前端已通过可发布密钥接收消息,但警报无法显示。已通过console.log确认回调函数正常执行,但警报仍无法渲染。

相关代码

回调逻辑代码

const chatChannel = supabase.channel(location)

chatChannel
  .on('broadcast', { event: 'emergency' }, (payload) => {
    app.displayPush({
        type: 'emergency',
        message: payload.message,
        locations: payload.locations,
        source: payload.source,
        id: payload.id
    })
  })
  .subscribe()

原displayPush函数代码

async function displayPush(info){
    if (info.type=='emergency'){
        let alert = document.createElement('div')
            alert.class = 'relative isolate flex items-center overflow-hidden bg-red-900 text-neutral-50'
            alert.height = '500px'
            alert.id = 'emergency-alert-'+info.id
            alert.innerHTML = `<p style="font-size: 20px;">${info.message}</p><br><p style="font-size: 10px;">${info.locations}</p><br><p style="font-size: 5px;">${payload.source}</p>`
    }
}

问题排查与修复

经检查,displayPush函数存在两处核心问题,同时还有一处细节错误需要修正:

  • 问题1:未将创建的警报元素添加到DOM
    代码仅创建了div元素,但未将其插入到页面DOM结构中,导致浏览器无法渲染该元素。需选择页面容器(如body或指定的警报容器),通过appendChild等方法将元素加入。
  • 问题2:引用未定义变量
    innerHTML中使用了payload.source,但payload是回调函数的参数,displayPush的入参为info,此处应改为info.source,否则会抛出未定义错误。
  • 细节修正:DOM元素类名属性错误
    原代码中alert.class写法错误,DOM元素的类名属性应为className,否则样式无法生效;同时height需通过style对象设置才能生效。

修复后的displayPush函数

async function displayPush(info){
    if (info.type=='emergency'){
        let alert = document.createElement('div')
        alert.className = 'relative isolate flex items-center overflow-hidden bg-red-900 text-neutral-50'
        alert.style.height = '500px'
        alert.id = 'emergency-alert-'+info.id
        alert.innerHTML = `<p style="font-size: 20px;">${info.message}</p><br><p style="font-size: 10px;">${info.locations}</p><br><p style="font-size: 5px;">${info.source}</p>`
        // 将警报元素添加到body中,可根据实际需求替换为指定容器
        document.body.appendChild(alert)
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.01 13:07:38