---
title: "WebSocket.onping | Grafana k6 documentation"
description: "A handler function for WebSocket connection ping event."
---

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

# WebSocket.onping

A handler for a WebSocket connection `ping` event. For multiple, simultaneous event handlers, use [`WebSocket.addEventListener()`](/docs/k6/next/javascript-api/k6-websockets/websocket/websocket-addeventlistener/).

### Example

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

JavaScript ![Copy code to clipboard](/media/images/icons/icon-copy-small-2.svg) Copy

```javascript
import { WebSocket } from 'k6/websockets';

export default function () {
  const ws = new WebSocket('wss://quickpizza.grafana.com/ws');

  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);
  };
}
```
