A read-only wrapper for [WebSocket event objects](https://developer.mozilla.org/en-US/docs/Web/API/MessageEvent). This class wraps browser WebSocket events and provides convenient access to event properties. It handles the conversion of binary data from JavaScript typed arrays
| 68 | |
| 69 | |
| 70 | class WebSocketEvent: |
| 71 | """ |
| 72 | A read-only wrapper for |
| 73 | [WebSocket event objects](https://developer.mozilla.org/en-US/docs/Web/API/MessageEvent). |
| 74 | |
| 75 | This class wraps browser WebSocket events and provides convenient access |
| 76 | to event properties. It handles the conversion of binary data from |
| 77 | JavaScript typed arrays to Python bytes-like objects. |
| 78 | |
| 79 | The most commonly used property is `event.data`, which contains the |
| 80 | message data for "message" events. |
| 81 | |
| 82 | ```python |
| 83 | def on_message(event): # The event is a WebSocketEvent instance. |
| 84 | # For text messages. |
| 85 | if isinstance(event.data, str): |
| 86 | print(f"Text: {event.data}") |
| 87 | else: |
| 88 | # For binary messages. |
| 89 | print(f"Binary: {len(event.data)} bytes") |
| 90 | ``` |
| 91 | """ |
| 92 | |
| 93 | def __init__(self, event): |
| 94 | """ |
| 95 | Create a WebSocketEvent wrapper from an underlying JavaScript |
| 96 | `event`. |
| 97 | """ |
| 98 | self._event = event |
| 99 | |
| 100 | def __getattr__(self, attr): |
| 101 | """ |
| 102 | Get an attribute `attr` from the underlying event object. |
| 103 | |
| 104 | Handles special conversion of binary data from JavaScript typed |
| 105 | arrays to Python `memoryview` objects. |
| 106 | """ |
| 107 | value = getattr(self._event, attr) |
| 108 | if attr == "data" and not isinstance(value, str): |
| 109 | if hasattr(value, "to_py"): |
| 110 | # Pyodide - convert JavaScript typed array to Python. |
| 111 | return value.to_py() |
| 112 | else: |
| 113 | # MicroPython - manually convert JS ArrayBuffer. |
| 114 | return memoryview(as_bytearray(value)) |
| 115 | return value |
| 116 | |
| 117 | |
| 118 | class WebSocket: |
no outgoing calls
no test coverage detected