pysxLearn by building

Foundations · Lesson 5 of 28

Handle browser events

Read bounded keyboard data and choose immediate browser event policy.

The server does not receive a live JavaScript Event object. It receives a typed snapshot containing supported fields. That boundary makes event data explicit and keeps a callback from acquiring arbitrary browser capabilities.

Some decisions cannot wait for a round trip. Preventing a key's default action or stopping propagation must be declared when registering the handler, so the browser can act immediately. An eventual Python callback is too late to undo a default action that already occurred.

Understand the moving parts

on_event combines a callback with its local policy. The key filter limits which keys invoke that callback. Modifier fields let the server distinguish an ordinary press from Shift or Control combinations without guessing from text.

Use semantic native buttons for activation. A clickable div needs keyboard and role behavior you would otherwise get for free. In the live exercise, the input retains focus while its event readout changes, so you can compare keys without clicking between every experiment.

Walk through the code

from pysx import BrowserEvent, Fragment, on_event, pysx, signal


def app() -> Fragment:
    report = signal("No key yet")

    def key(event: BrowserEvent) -> None:
        report.set(f"{event.key} · Shift: {event.shift} · Ctrl: {event.ctrl}")

    return pysx(t"""
        label(for="event-input"): "Press a key here"
        input(id="event-input" onKeydown={on_event(key)})
        output(id="event-report" ariaLive="polite"): {report}
    """)

on_event delivers a BrowserEvent. The handler records its actual key plus Shift and Ctrl flags, exactly as shown by the live readout. Reset demo clears the report by creating a new instance.

Try it live

Focus the event field. Press A, Shift+A and ArrowDown, then use Reset demo to clear the readout.

What to observe

The readout reports the actual key and modifier values delivered by your browser.

No key yet

Take this with you

Server callbacks receive snapshots; immediate cancellation belongs in local policy.