
本文详解浏览器端 WebSocket 的正确用法,指出常见误区(如错误引入 Node.js 的 ws 模块),并提供可直接运行的 HTML + JavaScript 示例,帮助开发者避免“Cannot use import statement outside a module”等语法错误。
本文详解浏览器端 websocket 的正确用法,指出常见误区(如错误引入 node.js 的 `ws` 模块),并提供可直接运行的 html + javascript 示例,帮助开发者避免“cannot use import statement outside a module”等语法错误。
WebSocket 是浏览器原生支持的全双工通信协议,无需安装或导入任何第三方模块——这一点至关重要。你遇到的 Uncaught SyntaxError: Cannot use import statement outside a module 错误,根源在于混淆了服务端与客户端的 WebSocket 实现:
- import WebSocket from 'ws' 和 require('ws') 属于 Node.js 环境下的服务端库(ws),完全不适用于浏览器;
- 浏览器内置 WebSocket 构造函数(全局对象),直接调用即可,无需 import 或 require。
✅ 正确做法:在 HTML 中通过 <script> 标签引入普通 JS 文件(非模块),或使用 type="module" 时仅导入 ES 模块(但 WebSocket 本身不是模块,不可导入)。</script>
以下是可立即运行的完整示例:
index.html
下载 Comet AI 浏览器,体验由 Perplexity AI 驱动的革命性上网方式。内置 AI 助手可实时总结网页、跨标签页对比信息、自动执行任务。告别繁琐操作,让 AI 成为你的浏览副驾,大幅提升研究与工作效率。支持 Windows、macOS、Android 和 iOS。
<meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>Browser WebSocket Demo</title><h2>WebSocket Client</h2>
<div id="status">Connecting...</div>
<button id="sendBtn" disabled>Send Message</button>
<script src="client.js"></script>
client.js(注意:不要使用 import/require)
// ✅ 直接使用浏览器原生 WebSocket
const ws = new WebSocket('wss://echo.websocket.org'); // 公共测试地址,支持 TLS
ws.onopen = () => {
console.log('✅ WebSocket connected');
document.getElementById('status').textContent = 'Connected';
document.getElementById('sendBtn').disabled = false;
};
ws.onmessage = (event) => {
console.log('? Received:', event.data);
alert(`Server replied: ${event.data}`);
};
ws.onerror = (error) => {
console.error('❌ WebSocket error:', error);
document.getElementById('status').textContent = 'Connection failed';
};
ws.onclose = () => {
console.log('? Connection closed');
document.getElementById('status').textContent = 'Disconnected';
};
// 示例:发送消息
document.getElementById('sendBtn').onclick = () => {
if (ws.readyState === WebSocket.OPEN) {
ws.send(`Hello at ${new Date().toISOString()}`);
}
};
⚠️ 关键注意事项:
- 不要在浏览器中 import 'ws' 或 require('ws'):该包仅用于 Node.js 服务端,浏览器中不存在 ws 模块,强行引入会导致解析失败;
- type="module" 仅对真正符合 ES Module 规范的脚本有效(如含 export/import 的文件),而调用原生 WebSocket 的脚本应作为普通脚本加载(即不用 type="module");
- 若必须使用模块化开发(如配合 Vite/Webpack),也不应导入 ws,而是直接使用全局 WebSocket —— 它在任何模块环境中均可访问;
- 协议需匹配:ws://(非加密)或 wss://(加密),确保后端服务已启用对应协议;
- 开发调试推荐使用 websocket.org/echo 或本地 wss://localhost:... 服务(需 HTTPS 上下文支持 wss)。
总结:浏览器 WebSocket 是开箱即用的 Web API,牢记「零依赖、无 import、全局可用」三大原则,即可避开绝大多数入门陷阱。
大量免费API接口:立即使用
涵盖生活服务API、金融科技API、企业工商API、等相关的API接口服务。免费API接口可安全、合规地连接上下游,为数据API应用能力赋能!










