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

JavaScript实现每隔K秒展示WebSocket推送新数据及自动滚动

WebSocket消息列表渲染实现

核心实现逻辑

  • 新增带滚动属性的列表容器,设置固定高度、超出内容时显示纵向滚动条
  • 收到WebSocket推送消息时,创建列表项插入到容器最顶部,满足新消息置顶要求
  • 每次插入新消息后,将容器滚动位置重置到顶部,实现自动滚动展示最新内容的效果
  • 做了基础容错处理:如果推送的是对象类型数据,自动序列化为字符串展示,避免出现[object Object]的渲染异常

完整可运行代码

<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>WebSocket消息列表</title>
    <style>
        /* 消息列表容器基础样式 */
        #msgList {
            max-height: 500px;
            width: 600px;
            margin: 20px 0;
            padding: 0;
            list-style: none;
            border: 1px solid #eee;
            overflow-y: auto; /* 内容超出高度时显示纵向滚动条 */
        }
        #msgList li {
            padding: 10px 15px;
            border-bottom: 1px solid #f0f0f0;
            word-break: break-all;
        }
        #msgList li:first-child {
            background-color: #f5f9ff; /* 最新消息加浅蓝背景,方便区分 */
        }
    </style>
    <script type="text/javascript">
        let ws = null; // 存储WebSocket实例,避免重复点击创建多个连接
        function myFunction() {
            // 已有可用连接时直接返回,不重复创建
            if (ws && ws.readyState === WebSocket.OPEN) return;

            if ("WebSocket" in window) {
                ws = new WebSocket("ws://localhost:9000/test");
                const msgList = document.getElementById('msgList');
                // 启动新连接时清空历史旧消息
                msgList.innerHTML = '';

                ws.onopen = function () {
                    console.log("connection opened");
                };
                ws.onmessage = function (evt) {
                    let data = evt.data;
                    // 非字符串类型数据统一转成字符串格式,避免渲染异常
                    if (typeof data !== 'string') {
                        data = JSON.stringify(data);
                    }
                    // 创建新的消息列表项
                    const newItem = document.createElement('li');
                    newItem.textContent = `[${new Date().toLocaleTimeString()}] ${data}`;
                    // 新消息插入到列表最顶部
                    msgList.prepend(newItem);
                    // 滚动位置重置到顶部,保证最新消息可见
                    msgList.scrollTop = 0;
                };
                ws.onclose = function () {
                    console.log("connection closed");
                    ws = null;
                }
            } else {
                alert("当前浏览器不支持WebSocket特性");
            }
        }
    </script>
</head>
<body>
<div id="sse">
    <a href="javascript:myFunction()">点击启动连接接收消息</a>
</div>
<!-- 消息展示列表容器 -->
<ul id="msgList"></ul>
</body>
</html>

可调配置说明

  • 列表可视高度:修改#msgList样式的max-height属性即可调整
  • 消息推送间隔K秒由服务端控制,前端只做被动接收渲染,不需要额外添加定时器逻辑
  • 如果需要平滑滚动效果,给#msgList增加scroll-behavior: smooth样式即可

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.30 03:09:38