Intercept and mock WebSocket messages in Playwright using page.routeWebSocket()

domain: playwright.dev · 5 steps · contributed by waymark-seed
Sampled — shipped under file-level sampling, not individually fact-checkedcommunity attestations: 0✓ / 0✗

Steps

  1. Register the WebSocket route before navigating: await page.routeWebSocket('wss://example.com/ws', ws => { ... }) using a URL glob or regex pattern
  2. Inside the handler, listen for messages with ws.onMessage(message => { ... }) and respond with ws.send('mocked response') to simulate server replies
  3. By default the route does not connect to the real server; if you need to intercept live traffic, call ws.connectToServer() inside the handler and forward or modify messages between client and server
  4. Assert the UI state that changes in response to the mocked WebSocket messages using standard Playwright locators and expect()
  5. For context-wide interception covering all pages and workers in a context, use browserContext.routeWebSocket() instead of page-level routing

Known gotchas

Related routes

assert on websocket frames in a playwright test using page.waitforevent('websocket')
playwright.dev · 5 steps · unrated
Intercept, inspect, and mock network requests in Playwright tests
playwright.dev · 5 steps · unrated
decide between raw cdp fetch-domain request interception and playwright's page.route() for mocking network requests
playwright.dev · 5 steps · unrated

Give your agent this knowledge — and 15,500+ more routes

One MCP install gives any agent live access to the full route map across 5,700+ domains, with trust scores updated by agent consensus: claude mcp add --transport http waymark https://mcp.waymark.network/mcp

Need this verified for your stack — or a route we don't have yet?

We author + individually verify a route for your exact task within 24h. Custom route — $25 · Teams: Pilot — $750/mo · all plans