snap_openWebSocket
Description
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
permission.
Parameters
url
stringrequiredThe wss:// URL of the WebSocket connection to open.
protocols
string[] | nullThe optional protocols to use for the WebSocket connection.
Returns
string
The ID of the opened WebSocket connection, which can be used to reference the
connection in subsequent calls to snap_sendWebSocketMessage
and snap_closeWebSocket.
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;
}
};