> For the complete documentation index, see [llms.txt](/llms.txt).

- Snap

# snap_openWebSocket

Open a WebSocket connection to the specified URL with optional protocols.

Note: This method is only available to snaps that have the [endowment:network-access](https://metamask-docs-git-imp-agt-scr-90-100-consensys-ddffed67.vercel.app/snaps/features/network-access/)permission.

## Parameters[​](#parameters "Direct link to Parameters")

object

required

The request parameters for the `snap_openWebSocket` method.

### url

string

required

The `wss://` URL of the WebSocket connection to open.

### protocols

string[]

The optional protocols to use for the WebSocket connection.

## Returns[​](#returns "Direct link to Returns")

string

The ID of the opened WebSocket connection, which can be used to reference the connection in subsequent calls to [snap_sendWebSocketMessage](https://metamask-docs-git-imp-agt-scr-90-100-consensys-ddffed67.vercel.app/snaps/reference/snaps-api/snap%5Fsendwebsocketmessage)and [snap_closeWebSocket](https://metamask-docs-git-imp-agt-scr-90-100-consensys-ddffed67.vercel.app/snaps/reference/snaps-api/snap%5Fclosewebsocket).

## Example

- Manifest
- Usage

```
{
  "initialPermissions": {
    "endowment:network-access": {}
  }
}

```

```
// Open a connection to a WebSocket server, e.g., in the JSON-RPC handler of
// the Snap:
snap.request({
  method: 'snap_openWebSocket',
  params: {
    url: 'wss://example.com/socket',
    protocols: ['protocol1', 'protocol2'], // Optional
  },
})

// Listen for events from the WebSocket connection in the `onWebSocketEvent`
// handler of the Snap:
export const onWebSocketEvent: OnWebSocketEventHandler = async ({ event }) => {
  switch (event.type) {
    case 'open':
      console.log(`WebSocket connection opened with origin ${event.origin}`)
      break
    case 'message':
      console.log(`WebSocket message received from origin ${event.origin}:`, event.data)
      break
    case 'close':
      console.log(`WebSocket connection closed with origin ${event.origin}`)
      break
    case 'error':
      console.error(`WebSocket error from origin ${event.origin}:`, event.error)
      break
  }
}

```
