# JavaScript Interop

- **Section:** Core Concepts
- **URL:** https://refast.fastapicloud.dev/docs/concepts/js-interop
- **Markdown:** https://refast.fastapicloud.dev/docs/concepts/js-interop.md
- **Source:** https://github.com/idling-mind/refast-docs/blob/main/docs/pages/concepts/js_interop.py
- **Live examples:** the widgets on this page need a browser; open the URL above to try them.
- **Applies to:** refast 0.12.2

## Overview

Sometimes you need client-side logic without a server roundtrip — animations, DOM
manipulation, localStorage access, or third-party JS library calls. Refast provides
four JavaScript interop methods on the `Context` object, split into two categories:

- **Event-handler callbacks** (`ctx.js()`, `ctx.bound_js()`) — returned as values and
  assigned to component event props. They run in the browser when the user interacts
  with the component, with no server roundtrip.
- **Imperative calls** (`ctx.call_js()`, `ctx.call_bound_js()`) — called with `await`
  inside an async Python callback. They send a WebSocket message that the browser
  executes immediately.

---

## ctx.js() — Client-Side Event Callback

Returns a `JsCallback` for use in event handler props (`on_click`, `on_change`, etc.).
No server roundtrip occurs; the code runs entirely in the browser.

```python
def js(
    self,
    code: str,
    *,
    debounce: int = 0,
    throttle: int = 0,
    stop_propagation: bool = False,
    prevent_default: bool = False,
    **bound_args,
) -> JsCallback:
```

Inside `code` the following globals are available:

| Name | Description |
|------|-------------|
| `event` | Event data — `value`, `checked`, `key`, `name`, `defaultPrevented`, etc. |
| `args` | Any `bound_args` passed from Python |
| `element` | The DOM element that triggered the event |
| `refast` | Helper object — `refast.invoke(callback, data)` calls a Python callback |

**Basic example:**

```python
Button(
    "Highlight",
    on_click=ctx.js(
        "document.getElementById('my-text').classList.add('bg-yellow-200')"
    ),
)
```

### Live demo: ctx.js()

Click the button — no server roundtrip, the browser handles it entirely.

This text can be highlighted by client-side JS.

**Reading event data:**

```python
Input(
    on_change=ctx.js("console.log('New value:', event.value)"),
)
```

**Debounce / throttle:**

```python
Input(
    on_change=ctx.js("console.log(event.value)", debounce=300),
)
```

**Event modifiers (`stop_propagation` & `prevent_default`):**

Pass `prevent_default=True` or `stop_propagation=True` directly into `ctx.js()`. For example, suppress the browser's default `Enter` key handling while invoking a Python callback:

```python
Input(
    placeholder="Press Enter...",
    on_keydown=ctx.js(
        '''
        if (event.key === 'Enter') {
            refast.invoke(args.on_enter, { value: event.value });
        }
        ''',
        on_enter=ctx.callback(handle_enter),
        prevent_default=True,
    ),
)
```

Inside JavaScript `code`, you can also check `event.defaultPrevented` and `event.propagationStopped`.

**Bridging back to Python with `refast.invoke`:**

Pass a serialized Python callback as a bound arg and call it from JS:

```python
Input(
    on_keydown=ctx.js(
        '''
        if (event.key === 'Enter') {
            refast.invoke(args.on_submit, { value: event.value });
        }
        ''',
        on_submit=ctx.callback(handle_submit),
    )
)
```

---

## ctx.bound_js() — Call a Component Method as an Event Handler

Returns a `BoundJsCallback` that calls a named method on the DOM element of the
component identified by `target_id`. Useful for components that expose imperative
APIs (canvas drawing, video players, dialogs, etc.).

```python
def bound_js(
    self,
    target_id: str,
    method_name: str,
    *args,
    debounce: int = 0,
    throttle: int = 0,
    stop_propagation: bool = False,
    prevent_default: bool = False,
    **kwargs,
) -> BoundJsCallback:
```

```python
Button("Play", on_click=ctx.bound_js("my-video", "play"))
Button("Show Dialog", on_click=ctx.bound_js("my-dialog", "showModal", stop_propagation=True))
Button("Eraser", on_click=ctx.bound_js("my-canvas", "setMode", "erase"))
```

Positional `args` and keyword `kwargs` are forwarded to the method call on the
element. Like `ctx.js()`, `ctx.bound_js()` also supports `stop_propagation=True` and `prevent_default=True`.

---

## ctx.call_js() — Imperatively Execute JS from Python

Awaitable. Sends a `js_exec` WebSocket message that the browser executes
immediately. Use this inside async Python callbacks when you need to trigger
browser-side behaviour after processing server-side logic.

```python
async def call_js(self, code: str, **args) -> None:
```

`args` are available inside `code` as the `args` object, exactly like `ctx.js()`.

```python
async def save_complete(ctx: Context):
    await db.save(ctx.event_data)
    await ctx.refresh()
    await ctx.call_js("confetti({ particleCount: 100 })")

async def focus_search(ctx: Context):
    await ctx.call_js(
        "document.getElementById(args.inputId)?.focus()",
        inputId="search-input",
    )
```

---

## ctx.call_bound_js() — Imperatively Call a Component Method from Python

Awaitable. Sends a `bound_method_call` WebSocket message that calls a named method
on a component's DOM element. Use inside async Python callbacks when the method call
depends on server-side data.

```python
async def call_bound_js(
    self,
    target_id: str,
    method_name: str,
    *args,
    **kwargs,
) -> None:
```

```python
async def load_drawing(ctx: Context):
    paths = await db.get_drawing(ctx.event_data["id"])
    await ctx.call_bound_js("my-canvas", "loadPaths", paths=paths)

async def draw_shape(ctx: Context):
    await ctx.call_bound_js("my-canvas", "drawShape", "circle", x=100, y=200)
```

---

## Summary

| Method | Type | Returns | Server Roundtrip? | Modifiers Supported |
|--------|------|---------|-------------------|---------------------|
| `ctx.js(code, ...)` | Event-handler prop | `JsCallback` | No | `stop_propagation`, `prevent_default` |
| `ctx.bound_js(id, method, ...)` | Event-handler prop | `BoundJsCallback` | No | `stop_propagation`, `prevent_default` |
| `await ctx.call_js(code, **args)` | Imperative (in callback) | `None` | No — sent via WS | N/A (runs imperatively) |
| `await ctx.call_bound_js(id, method)` | Imperative (in callback) | `None` | No — sent via WS | N/A (runs imperatively) |
| `ctx.callback(fn, ...)` | Event-handler prop | `Callback` | Yes | `stop_propagation`, `prevent_default` |
| `ctx.save_prop(name, ...)` | Event-handler prop | `SaveProp` | No | `stop_propagation`, `prevent_default` |
| `ctx.chain(actions, ...)` | Event-handler prop | `ChainedAction` | Depends | `stop_propagation`, `prevent_default` |

---

## When to Use JS vs Python Callbacks

**Use JS callbacks (`ctx.js`, `ctx.bound_js`)** for:
- UI-only interactions (toggle class, scroll, focus)
- Performance-sensitive actions (hover effects, real-time input feedback)
- Browser API access (clipboard, geolocation, media)

**Use imperative JS (`ctx.call_js`, `ctx.call_bound_js`)** for:
- Triggering browser behaviour *after* server-side logic completes
- Animations or third-party library calls that depend on server data

**Use Python callbacks (`ctx.callback`)** for:
- Business logic, data processing
- State changes that affect the UI
- Database or API operations

---

## Next Steps

- [Building Components](https://refast.fastapicloud.dev/docs/advanced/component-dev) — Custom component development
- [Building Extensions](https://refast.fastapicloud.dev/docs/advanced/extension-dev) — Packaging reusable functionality

---

Part of the Refast documentation: [all pages](https://refast.fastapicloud.dev/llms.txt), [everything on one page](https://refast.fastapicloud.dev/llms-full.txt), [search](https://refast.fastapicloud.dev/api/search?q=save_prop).
