Menu

Important: This documentation is about an older version. It's relevant only to the release noted, many of the features and functions have been updated or replaced. Please view the current version.

Open source

WebSocket.onping

A handler for a WebSocket connection ping event. For multiple, simultaneous event handlers, use WebSocket.addEventListener().

Example

A k6 script that initiates a WebSocket connection and sets up a handler for the ping event.

JavaScript
import { WebSocket } from 'k6/experimental/websockets';

export default function () {
  const ws = new WebSocket('wss://test-api.k6.io/ws/crocochat/publicRoom/');

  ws.onping = () => {
    console.log('A ping happened!');
    ws.close();
  };

  ws.onclose = () => {
      console.log('WebSocket connection closed!');
  }

  ws.onopen = () => {
      ws.send(JSON.stringify({ 'event': 'SET_NAME', 'new_name': `Croc ${__VU}` }));
  }
  ws.onerror = (err) => {
      console.log(err)
  }
}