microsoft/playwright · error · Error

Cannot send a message before connecting to the server

Error message

Cannot send a message before connecting to the server

What it means

Error "Cannot send a message before connecting to the server" thrown in microsoft/playwright.

Source

Thrown at packages/injected/src/webSocketMock.ts:258

    _apiEnsureOpened() {
      // This is called at the end of the route handler. If we did not connect to the server,
      // assume that websocket will be fully mocked. In this case, pretend that server
      // connection is established right away.
      if (!this._ws)
        this._ensureOpened();
    }

    _apiSendToPage(message: WebSocketMessage) {
      // Calling "sendToPage()" from the route handler. Allow this for easier testing.
      this._ensureOpened();
      if (this.readyState !== WebSocketMock.OPEN)
        throw new DOMException(`WebSocket is already in CLOSING or CLOSED state.`);
      this.dispatchEvent(new MessageEvent('message', { data: message, origin: this._origin, cancelable: true }));
    }

    _apiSendToServer(message: WebSocketMessage) {
      if (!this._ws)
        throw new Error('Cannot send a message before connecting to the server');
      if (this._ws.readyState === WebSocketMock.CONNECTING)
        this._wsBufferedMessages.push(message);
      else
        this._ws.send(message);
    }

    _apiConnect() {
      if (this._ws)
        throw new Error('Can only connect to the server once');

      this._ws = new NativeWebSocket(this.url, this._protocols);
      this._ws.binaryType = this._binaryType;

      this._ws.onopen = () => {
        for (const message of this._wsBufferedMessages)
          this._ws!.send(message);
        this._wsBufferedMessages = [];
        this._ensureOpened();

View on GitHub (pinned to c8fc3bf8d3)

When it happens

Trigger: Thrown at packages/injected/src/webSocketMock.ts:258 when the library encounters an invalid state.

Common situations: See trigger scenarios.


AI-assisted analysis of microsoft/playwright@c8fc3bf8d3 (2026-08-12). Data as JSON: /api/errors/3de4b64f4cf02de1. Report an issue: GitHub.