websocket-devtools-extension

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

WebSocket DevTools Extension

WebSocket DevTools Extension

Skill by ara.so — Devtools Skills collection
WebSocket DevTools is a Chrome/Edge browser extension that provides comprehensive WebSocket debugging capabilities including real-time message monitoring, bidirectional message simulation, traffic blocking, and favorites management - all within the browser's native DevTools interface.
ara.so开发的工具——Devtools工具集
WebSocket DevTools是一款Chrome/Edge浏览器扩展,提供全面的WebSocket调试功能,包括实时消息监控、双向消息模拟、流量拦截和收藏管理,所有功能都集成在浏览器原生的DevTools界面中。

Installation

安装

Chrome Web Store

Chrome Web Store

bash
undefined
bash
undefined

Visit and install from:

访问以下链接安装:

After installation:

安装完成后:

1. Open any webpage with WebSocket connections

1. 打开任何包含WebSocket连接的网页

2. Press F12 to open DevTools

2. 按F12打开DevTools

3. Navigate to "WebSocket DevTools" tab

3. 切换到「WebSocket DevTools」标签页

undefined
undefined

Microsoft Edge Add-ons

Microsoft Edge Add-ons

bash
undefined
bash
undefined

Visit and install from:

访问以下链接安装:

After installation, same steps as Chrome

安装完成后,操作步骤与Chrome一致

undefined
undefined

Developer Mode (Local Installation)

开发者模式(本地安装)

bash
undefined
bash
undefined

Clone the repository

克隆仓库

In Chrome/Edge:

在Chrome/Edge中:

1. Navigate to chrome://extensions/ (or edge://extensions/)

1. 打开 chrome://extensions/(或 edge://extensions/)

2. Enable "Developer mode"

2. 启用「开发者模式」

3. Click "Load unpacked"

3. 点击「加载已解压的扩展程序」

4. Select the extension directory

4. 选择扩展所在目录

undefined
undefined

Core Concepts

核心概念

Background Monitoring

后台监控

The extension automatically captures all WebSocket connections and messages in the background, even when DevTools is closed. This means:
  • No missed connections if you open DevTools after WebSocket establishment
  • Persistent message history during page lifetime
  • Zero configuration required
该扩展会在后台自动捕获所有WebSocket连接和消息,即使DevTools处于关闭状态。这意味着:
  • 即使在WebSocket建立后才打开DevTools,也不会错过任何连接
  • 在页面生命周期内保留消息历史记录
  • 无需任何配置

Traffic Control

流量控制

  • Message Blocking: Intercept and block messages in either direction (client→server or server→client)
  • Simulation: Send custom messages as if they came from client or server
  • Pattern Matching: Block messages based on content, type, or URL patterns
  • 消息拦截:拦截并阻断任意方向的消息(客户端→服务器 或 服务器→客户端)
  • 消息模拟:发送自定义消息,模拟客户端或服务器的消息发送行为
  • 模式匹配:根据内容、类型或URL模式阻断消息

Favorites System

收藏系统

Save frequently used messages for quick replay and testing scenarios.
保存常用消息,以便快速重放和测试场景。

Key Features & Usage

核心功能与使用方法

1. Monitoring WebSocket Connections

1. 监控WebSocket连接

Once installed, the extension automatically captures all WebSocket activity:
javascript
// Example WebSocket connection that will be automatically monitored
const ws = new WebSocket('wss://example.com/socket');

ws.onopen = () => {
  console.log('Connected');
  ws.send(JSON.stringify({ type: 'auth', token: 'user-token' }));
};

ws.onmessage = (event) => {
  console.log('Received:', event.data);
  // All messages appear in WebSocket DevTools panel
};

ws.onerror = (error) => {
  console.error('WebSocket error:', error);
};

// The extension captures:
// - Connection URL and protocol
// - All sent and received messages
// - Timestamps and message sizes
// - Connection state changes
安装完成后,扩展会自动捕获所有WebSocket活动:
javascript
// 示例:会被自动监控的WebSocket连接
const ws = new WebSocket('wss://example.com/socket');

ws.onopen = () => {
  console.log('已连接');
  ws.send(JSON.stringify({ type: 'auth', token: 'user-token' }));
};

ws.onmessage = (event) => {
  console.log('收到消息:', event.data);
  // 所有消息都会显示在WebSocket DevTools面板中
};

ws.onerror = (error) => {
  console.error('WebSocket错误:', error);
};

// 扩展会捕获以下信息:
// - 连接URL和协议
// - 所有发送和接收的消息
// - 时间戳和消息大小
// - 连接状态变化

2. Message Simulation

2. 消息模拟

Send custom messages to test client/server behavior:
Simulate Server → Client Message
javascript
// In DevTools "Simulate" tab, send this JSON:
{
  "type": "notification",
  "title": "Test Alert",
  "message": "This is a simulated server message",
  "timestamp": 1704067200000
}

// Your client-side handler receives this as if from the server:
ws.onmessage = (event) => {
  const data = JSON.parse(event.data);
  if (data.type === 'notification') {
    showNotification(data.title, data.message);
  }
};
Simulate Client → Server Message
javascript
// In DevTools "Simulate" tab, choose "Client→Server" direction
{
  "action": "subscribe",
  "channel": "trades",
  "symbol": "BTC/USD"
}

// Your server receives this as if the client sent it
// Useful for testing server-side handlers without modifying client code
发送自定义消息以测试客户端/服务器行为:
模拟服务器→客户端消息
javascript
// 在DevTools的「模拟」标签页中,发送以下JSON:
{
  "type": "notification",
  "title": "测试通知",
  "message": "这是一条模拟的服务器消息",
  "timestamp": 1704067200000
}

// 客户端处理程序会像接收真实服务器消息一样接收该消息:
ws.onmessage = (event) => {
  const data = JSON.parse(event.data);
  if (data.type === 'notification') {
    showNotification(data.title, data.message);
  }
};
模拟客户端→服务器消息
javascript
// 在DevTools的「模拟」标签页中,选择「客户端→服务器」方向
{
  "action": "subscribe",
  "channel": "trades",
  "symbol": "BTC/USD"
}

// 服务器会像接收真实客户端消息一样接收该消息
// 无需修改客户端代码即可测试服务器端处理逻辑

3. Message Blocking

3. 消息拦截

Block specific messages to test error handling and edge cases:
Block Pattern Example
javascript
// Your application code
const ws = new WebSocket('wss://api.example.com/feed');

ws.onmessage = (event) => {
  const data = JSON.parse(event.data);
  
  // Test what happens when 'price_update' messages are blocked
  if (data.type === 'price_update') {
    updatePrice(data.symbol, data.price);
  }
};

// In DevTools:
// 1. Go to "Block" tab
// 2. Add block rule: { "type": "price_update" }
// 3. Test your app's behavior when price updates stop arriving
// 4. Verify your timeout/fallback logic works correctly
Bidirectional Blocking
javascript
// Block outgoing messages to test retry logic
const sendWithRetry = async (data, maxRetries = 3) => {
  for (let i = 0; i < maxRetries; i++) {
    try {
      ws.send(JSON.stringify(data));
      
      // If blocked in DevTools, this tests your retry mechanism
      await waitForAck(data.id);
      return;
    } catch (error) {
      if (i === maxRetries - 1) throw error;
      await sleep(1000 * Math.pow(2, i));
    }
  }
};
阻断特定消息以测试错误处理和边缘情况:
拦截模式示例
javascript
// 应用代码
const ws = new WebSocket('wss://api.example.com/feed');

ws.onmessage = (event) => {
  const data = JSON.parse(event.data);
  
  // 测试当'price_update'消息被阻断时的情况
  if (data.type === 'price_update') {
    updatePrice(data.symbol, data.price);
  }
};

// 在DevTools中:
// 1. 切换到「拦截」标签页
// 2. 添加拦截规则:{ "type": "price_update" }
// 3. 测试价格更新停止时应用的行为
// 4. 验证超时/降级逻辑是否正常工作
双向拦截
javascript
// 阻断 outgoing 消息以测试重试逻辑
const sendWithRetry = async (data, maxRetries = 3) => {
  for (let i = 0; i < maxRetries; i++) {
    try {
      ws.send(JSON.stringify(data));
      
      // 如果在DevTools中被阻断,将测试重试机制
      await waitForAck(data.id);
      return;
    } catch (error) {
      if (i === maxRetries - 1) throw error;
      await sleep(1000 * Math.pow(2, i));
    }
  }
};

4. JSON Message Inspector

4. JSON消息检查器

Automatically parses and formats JSON messages:
javascript
// When your WebSocket sends/receives JSON:
const message = {
  event: 'order_placed',
  data: {
    orderId: '12345',
    symbol: 'BTC/USD',
    side: 'buy',
    quantity: 0.5,
    price: 45000,
    timestamp: new Date().toISOString()
  }
};

ws.send(JSON.stringify(message));

// In DevTools:
// - Messages automatically parsed and pretty-printed
// - Tree view for nested objects
// - Copy formatted JSON
// - Search within message content
自动解析并格式化JSON消息:
javascript
// 当WebSocket发送/接收JSON时:
const message = {
  event: 'order_placed',
  data: {
    orderId: '12345',
    symbol: 'BTC/USD',
    side: 'buy',
    quantity: 0.5,
    price: 45000,
    timestamp: new Date().toISOString()
  }
};

ws.send(JSON.stringify(message));

// 在DevTools中:
// - 消息会被自动解析并格式化显示
// - 嵌套对象支持树形视图
// - 可复制格式化后的JSON
// - 可在消息内容中搜索

5. Favorites Management

5. 收藏管理

Save and organize frequently used messages:
javascript
// Common test messages to save as favorites:

// 1. Authentication test
{
  "type": "auth",
  "username": "testuser",
  "token": "${TEST_AUTH_TOKEN}"
}

// 2. Market data subscription
{
  "action": "subscribe",
  "channels": ["ticker", "trades", "orderbook"],
  "symbols": ["BTC/USD", "ETH/USD"]
}

// 3. Error scenario test
{
  "type": "error",
  "code": 401,
  "message": "Unauthorized"
}

// Use favorites to:
// - Quickly replay common scenarios
// - Build test suites
// - Document API message formats
// - Share testing patterns with team
保存并整理常用消息:
javascript
// 可保存为收藏的常见测试消息:

// 1. 认证测试
{
  "type": "auth",
  "username": "testuser",
  "token": "${TEST_AUTH_TOKEN}"
}

// 2. 市场数据订阅
{
  "action": "subscribe",
  "channels": ["ticker", "trades", "orderbook"],
  "symbols": ["BTC/USD", "ETH/USD"]
}

// 3. 错误场景测试
{
  "type": "error",
  "code": 401,
  "message": "未授权"
}

// 使用收藏功能可:
// - 快速重放常见场景
// - 构建测试套件
// - 记录API消息格式
// - 与团队共享测试模式

Common Patterns

常见测试模式

Testing WebSocket Reconnection Logic

测试WebSocket重连逻辑

javascript
// Your reconnection logic
class WebSocketClient {
  constructor(url) {
    this.url = url;
    this.reconnectAttempts = 0;
    this.maxReconnectAttempts = 5;
    this.connect();
  }

  connect() {
    this.ws = new WebSocket(this.url);
    
    this.ws.onopen = () => {
      console.log('Connected');
      this.reconnectAttempts = 0;
    };
    
    this.ws.onclose = () => {
      console.log('Disconnected');
      this.reconnect();
    };
  }

  reconnect() {
    if (this.reconnectAttempts >= this.maxReconnectAttempts) {
      console.error('Max reconnection attempts reached');
      return;
    }
    
    this.reconnectAttempts++;
    const delay = Math.min(1000 * Math.pow(2, this.reconnectAttempts), 30000);
    
    setTimeout(() => this.connect(), delay);
  }
}

// Testing with WebSocket DevTools:
// 1. Monitor the initial connection
// 2. Use DevTools to block all messages (simulates network issue)
// 3. Verify reconnection attempts in the connection list
// 4. Check exponential backoff timing
// 5. Remove block and verify successful reconnection
javascript
// 重连逻辑代码
class WebSocketClient {
  constructor(url) {
    this.url = url;
    this.reconnectAttempts = 0;
    this.maxReconnectAttempts = 5;
    this.connect();
  }

  connect() {
    this.ws = new WebSocket(this.url);
    
    this.ws.onopen = () => {
      console.log('已连接');
      this.reconnectAttempts = 0;
    };
    
    this.ws.onclose = () => {
      console.log('已断开连接');
      this.reconnect();
    };
  }

  reconnect() {
    if (this.reconnectAttempts >= this.maxReconnectAttempts) {
      console.error('已达到最大重连次数');
      return;
    }
    
    this.reconnectAttempts++;
    const delay = Math.min(1000 * Math.pow(2, this.reconnectAttempts), 30000);
    
    setTimeout(() => this.connect(), delay);
  }
}

// 使用WebSocket DevTools测试:
// 1. 监控初始连接
// 2. 使用DevTools阻断所有消息(模拟网络问题)
// 3. 在连接列表中验证重连尝试
// 4. 检查指数退避计时
// 5. 取消阻断并验证重连成功

Testing Message Order and Race Conditions

测试消息顺序与竞态条件

javascript
// Your application code
class MessageQueue {
  constructor(ws) {
    this.ws = ws;
    this.queue = [];
    this.processing = false;
  }

  async send(message) {
    this.queue.push(message);
    if (!this.processing) {
      await this.processQueue();
    }
  }

  async processQueue() {
    this.processing = true;
    
    while (this.queue.length > 0) {
      const message = this.queue.shift();
      this.ws.send(JSON.stringify(message));
      await this.waitForAck(message.id);
    }
    
    this.processing = false;
  }
}

// Testing with WebSocket DevTools:
// 1. Send multiple messages rapidly using Simulate tab
// 2. Observe order in message list
// 3. Block acknowledgment messages to test queue behavior
// 4. Verify no race conditions or message loss
javascript
// 应用代码
class MessageQueue {
  constructor(ws) {
    this.ws = ws;
    this.queue = [];
    this.processing = false;
  }

  async send(message) {
    this.queue.push(message);
    if (!this.processing) {
      await this.processQueue();
    }
  }

  async processQueue() {
    this.processing = true;
    
    while (this.queue.length > 0) {
      const message = this.queue.shift();
      this.ws.send(JSON.stringify(message));
      await this.waitForAck(message.id);
    }
    
    this.processing = false;
  }
}

// 使用WebSocket DevTools测试:
// 1. 使用模拟标签页快速发送多条消息
// 2. 在消息列表中观察顺序
// 3. 阻断确认消息以测试队列行为
// 4. 验证无竞态条件或消息丢失

Testing Binary Message Handling

测试二进制消息处理

javascript
// Your binary WebSocket handler
const ws = new WebSocket('wss://example.com/binary');
ws.binaryType = 'arraybuffer';

ws.onmessage = (event) => {
  if (event.data instanceof ArrayBuffer) {
    const view = new DataView(event.data);
    const messageType = view.getUint8(0);
    const messageId = view.getUint32(1, true);
    
    console.log('Binary message:', messageType, messageId);
    
    // Process binary data
    processBinaryMessage(event.data);
  }
};

// In WebSocket DevTools:
// - Binary messages shown with size and hex preview
// - Can inspect binary content
// - Monitor binary message frequency
// - Block binary messages to test fallback logic
javascript
// 二进制WebSocket处理代码
const ws = new WebSocket('wss://example.com/binary');
ws.binaryType = 'arraybuffer';

ws.onmessage = (event) => {
  if (event.data instanceof ArrayBuffer) {
    const view = new DataView(event.data);
    const messageType = view.getUint8(0);
    const messageId = view.getUint32(1, true);
    
    console.log('二进制消息:', messageType, messageId);
    
    // 处理二进制数据
    processBinaryMessage(event.data);
  }
};

// 在WebSocket DevTools中:
// - 二进制消息会显示大小和十六进制预览
// - 可检查二进制内容
// - 监控二进制消息频率
// - 阻断二进制消息以测试降级逻辑

Socket.IO Integration

Socket.IO集成

javascript
// Socket.IO uses WebSocket under the hood
const socket = io('https://example.com', {
  transports: ['websocket'],
  auth: {
    token: process.env.SOCKET_IO_TOKEN
  }
});

socket.on('connect', () => {
  console.log('Socket.IO connected');
  
  // All these events are visible in WebSocket DevTools
  socket.emit('join_room', { room: 'trading' });
});

socket.on('price_update', (data) => {
  console.log('Price:', data);
});

// In WebSocket DevTools:
// - See Socket.IO protocol messages (42["event",data])
// - Monitor heartbeat (ping/pong) messages
// - Simulate Socket.IO events by sending proper format
// - Block specific event types for testing
javascript
// Socket.IO底层使用WebSocket
const socket = io('https://example.com', {
  transports: ['websocket'],
  auth: {
    token: process.env.SOCKET_IO_TOKEN
  }
});

socket.on('connect', () => {
  console.log('Socket.IO已连接');
  
  // 所有这些事件都会在WebSocket DevTools中可见
  socket.emit('join_room', { room: 'trading' });
});

socket.on('price_update', (data) => {
  console.log('价格:', data);
});

// 在WebSocket DevTools中:
// - 可查看Socket.IO协议消息(42["event",data])
// - 监控心跳(ping/pong)消息
// - 通过发送正确格式模拟Socket.IO事件
// - 阻断特定事件类型进行测试

Configuration

配置

The extension works with zero configuration, but you can customize behavior:
该扩展无需配置即可使用,但你可以自定义行为:

Extension Settings (in DevTools panel)

扩展设置(在DevTools面板中)

javascript
// Settings accessible in WebSocket DevTools panel:

// 1. Message Filter
// - Filter by direction (sent/received)
// - Filter by content (text search)
// - Filter by connection URL

// 2. Display Options
// - Auto-scroll to latest message
// - Show/hide timestamps
// - Message format (raw/formatted JSON)
// - Max messages to display (performance)

// 3. Block Rules
// - Enable/disable all blocking
// - Export/import block rules
// - Match type: exact, contains, regex

// 4. Favorites
// - Organize by tags
// - Export/import favorites
// - Quick access shortcuts
javascript
// 可在WebSocket DevTools面板中访问以下设置:

// 1. 消息过滤
// - 按方向过滤(发送/接收)
// - 按内容过滤(文本搜索)
// - 按连接URL过滤

// 2. 显示选项
// - 自动滚动到最新消息
// - 显示/隐藏时间戳
// - 消息格式(原始/格式化JSON)
// - 最大显示消息数(性能优化)

// 3. 拦截规则
// - 启用/禁用所有拦截
// - 导出/导入拦截规则
// - 匹配类型:精确匹配、包含匹配、正则匹配

// 4. 收藏
// - 按标签分类
// - 导出/导入收藏
// - 快速访问快捷键

Troubleshooting

故障排除

DevTools Panel Not Showing

DevTools面板未显示

javascript
// Issue: "WebSocket DevTools" tab not visible in DevTools

// Solutions:
// 1. Verify extension is enabled in chrome://extensions/
// 2. Refresh the page after enabling extension
// 3. Check if extension has permissions for the current site
// 4. Try opening DevTools before navigating to the page
// 5. Check browser console for extension errors
javascript
// 问题:DevTools中未显示「WebSocket DevTools」标签页

// 解决方案:
// 1. 在chrome://extensions/中验证扩展已启用
// 2. 启用扩展后刷新页面
// 3. 检查扩展是否拥有当前站点的权限
// 4. 尝试在导航到页面之前打开DevTools
// 5. 检查浏览器控制台中的扩展错误

Messages Not Being Captured

消息未被捕获

javascript
// Issue: WebSocket connections not appearing

// Check your WebSocket creation:
const ws = new WebSocket('wss://example.com/socket');

// Ensure:
// 1. Using standard WebSocket API (not custom implementations)
// 2. Connection established after extension loaded
// 3. No Content Security Policy blocking
// 4. Not using WebWorkers (limited support)

// For iframes:
// Extension supports iframe WebSockets
// Ensure iframe has same origin or CORS configured
javascript
// 问题:WebSocket连接未显示

// 检查WebSocket创建代码:
const ws = new WebSocket('wss://example.com/socket');

// 确保:
// 1. 使用标准WebSocket API(而非自定义实现)
// 2. 连接在扩展加载后建立
// 3. 没有内容安全策略(CSP)阻止连接
// 4. 未使用WebWorkers(支持有限)

// 对于iframe:
// 扩展支持iframe中的WebSocket
// 确保iframe同源或已配置CORS

Simulation Not Working

模拟功能不工作

javascript
// Issue: Simulated messages not received by application

// Verify message format matches server expectations:
// Wrong:
{
  type: "message",
  data: "test"  // Missing fields
}

// Correct:
{
  type: "message",
  id: "msg-123",
  timestamp: 1704067200000,
  data: "test",
  checksum: "abc123"  // Include all required fields
}

// Check:
// 1. JSON is valid (use built-in validator)
// 2. Message structure matches protocol
// 3. Direction is correct (Client→Server vs Server→Client)
// 4. WebSocket is connected (not closed)
javascript
// 问题:模拟消息未被应用接收

// 验证消息格式是否符合服务器预期:
// 错误示例:
{
  type: "message",
  data: "test"  // 缺少必要字段
}

// 正确示例:
{
  type: "message",
  id: "msg-123",
  timestamp: 1704067200000,
  data: "test",
  checksum: "abc123"  // 包含所有必要字段
}

// 检查:
// 1. JSON格式有效(使用内置验证器)
// 2. 消息结构符合协议要求
// 3. 方向正确(客户端→服务器 vs 服务器→客户端)
// 4. WebSocket处于连接状态(未关闭)

Block Rules Not Applied

拦截规则未生效

javascript
// Issue: Messages not being blocked despite rules

// Check block rule format:
// Exact match (case-sensitive):
{
  "type": "heartbeat"
}

// Contains match:
{
  "*message*": "*error*"
}

// Regex match:
{
  "type": "/^(ping|pong)$/"
}

// Common issues:
// 1. Rule disabled in Block tab
// 2. Wrong match type selected
// 3. Typo in field name
// 4. Message format different than expected (binary vs text)
javascript
// 问题:已设置规则但消息未被阻断

// 检查拦截规则格式:
// 精确匹配(区分大小写):
{
  "type": "heartbeat"
}

// 包含匹配:
{
  "*message*": "*error*"
}

// 正则匹配:
{
  "type": "/^(ping|pong)$/"
}

// 常见问题:
// 1. 规则在「拦截」标签页中被禁用
// 2. 选择了错误的匹配类型
// 3. 字段名称拼写错误
// 4. 消息格式与预期不符(二进制 vs 文本)

Performance Issues with High Message Volume

高消息量下的性能问题

javascript
// Issue: DevTools slow with many messages

// Optimization:
// 1. Reduce max messages displayed (Settings → Max Messages: 1000)
// 2. Use filters to show only relevant messages
// 3. Clear old connections periodically
// 4. Disable auto-scroll for high-frequency messages

// For high-frequency trading apps:
const ws = new WebSocket('wss://hft.example.com/feed');

// Consider:
// - Using message sampling in DevTools filters
// - Only monitoring during specific test scenarios
// - Clearing message history when not actively debugging
javascript
// 问题:消息过多时DevTools运行缓慢

// 优化方案:
// 1. 减少最大显示消息数(设置→最大消息数:1000)
// 2. 使用过滤器仅显示相关消息
// 3. 定期清除旧连接
// 4. 高频消息场景下禁用自动滚动

// 对于高频交易应用:
const ws = new WebSocket('wss://hft.example.com/feed');

// 建议:
// - 在DevTools过滤器中使用消息采样
// - 仅在特定测试场景下监控
// - 不活跃调试时清除消息历史

Advanced Usage

进阶用法

Testing WebSocket Security

测试WebSocket安全性

javascript
// Test authentication flows
const ws = new WebSocket('wss://secure.example.com/socket');

ws.onopen = () => {
  // Test invalid token
  ws.send(JSON.stringify({
    type: 'auth',
    token: 'invalid-token'
  }));
};

ws.onmessage = (event) => {
  const data = JSON.parse(event.data);
  
  if (data.type === 'auth_failed') {
    // Verify proper error handling
    console.error('Authentication failed:', data.reason);
  }
};

// In WebSocket DevTools:
// 1. Save valid auth message as favorite
// 2. Create variations with invalid tokens
// 3. Test different error scenarios
// 4. Verify server responses and client handling
javascript
// 测试认证流程
const ws = new WebSocket('wss://secure.example.com/socket');

ws.onopen = () => {
  // 测试无效令牌
  ws.send(JSON.stringify({
    type: 'auth',
    token: 'invalid-token'
  }));
};

ws.onmessage = (event) => {
  const data = JSON.parse(event.data);
  
  if (data.type === 'auth_failed') {
    // 验证错误处理是否正确
    console.error('认证失败:', data.reason);
  }
};

// 在WebSocket DevTools中:
// 1. 将有效认证消息保存为收藏
// 2. 创建含无效令牌的变体
// 3. 测试不同错误场景
// 4. 验证服务器响应和客户端处理逻辑

Multi-Connection Testing

多连接测试

javascript
// Test multiple simultaneous connections
const connections = [];

for (let i = 0; i < 5; i++) {
  const ws = new WebSocket(`wss://example.com/socket?client=${i}`);
  
  ws.onopen = () => {
    console.log(`Client ${i} connected`);
  };
  
  connections.push(ws);
}

// In WebSocket DevTools:
// - See all 5 connections listed separately
// - Monitor messages for each connection
// - Simulate messages to specific connections
// - Test connection-specific logic
// - Verify server handles multiple clients correctly
javascript
// 测试多个同时连接
const connections = [];

for (let i = 0; i < 5; i++) {
  const ws = new WebSocket(`wss://example.com/socket?client=${i}`);
  
  ws.onopen = () => {
    console.log(`客户端 ${i} 已连接`);
  };
  
  connections.push(ws);
}

// 在WebSocket DevTools中:
// - 可查看全部5个独立连接
// - 监控每个连接的消息
// - 向特定连接发送模拟消息
// - 测试连接专属逻辑
// - 验证服务器是否能正确处理多个客户端

Integration with Automated Testing

与自动化测试集成

javascript
// While extension is manual, you can prepare test scenarios

// 1. Document test cases as favorites
const testCases = [
  { name: 'Valid Login', message: { type: 'auth', token: 'valid' } },
  { name: 'Invalid Login', message: { type: 'auth', token: 'invalid' } },
  { name: 'Subscribe', message: { type: 'subscribe', channel: 'prices' } }
];

// 2. Export favorites for team sharing
// 3. Create block rule sets for different test scenarios
// 4. Document expected behaviors in favorite descriptions

// This helps manual QA and developers test consistently
javascript
// 虽然扩展是手动工具,但你可以准备测试场景

// 1. 将测试用例保存为收藏
const testCases = [
  { name: '有效登录', message: { type: 'auth', token: 'valid' } },
  { name: '无效登录', message: { type: 'auth', token: 'invalid' } },
  { name: '订阅', message: { type: 'subscribe', channel: 'prices' } }
];

// 2. 导出收藏供团队共享
// 3. 为不同测试场景创建拦截规则集
// 4. 在收藏描述中记录预期行为

// 这有助于手动QA和开发人员进行一致性测试

Best Practices

最佳实践

  1. Always enable background monitoring before loading pages with WebSockets
  2. Save complex test messages as favorites for repeatability
  3. Use message filtering to focus on specific message types during debugging
  4. Export favorites and block rules to share testing scenarios with team
  5. Clear old connections periodically to maintain performance
  6. Test both directions - client→server and server→client simulation
  7. Document your WebSocket protocol using favorites as examples
  8. Use blocking to test error handling and recovery logic
  9. Monitor message frequency to identify performance issues
  10. Check iframe WebSocket support if working with embedded content
  1. 在加载含WebSocket的页面前始终启用后台监控
  2. 将复杂测试消息保存为收藏以保证可重复性
  3. 使用消息过滤在调试时聚焦特定消息类型
  4. 导出收藏和拦截规则与团队共享测试场景
  5. 定期清除旧连接以维持性能
  6. 测试双向消息——客户端→服务器和服务器→客户端模拟
  7. 使用收藏作为示例记录WebSocket协议
  8. 使用拦截功能测试错误处理和恢复逻辑
  9. 监控消息频率以识别性能问题
  10. 若处理嵌入式内容,请检查iframe的WebSocket支持情况

Resources

资源