# Desktop Notifications

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

Desktop notifications let your application send native, system-level alerts to the user's
desktop or mobile device. Unlike toast notifications, desktop notifications:
- Display outside the browser window.
- Can persist when your web application is minimized or runs in the background.
- Can receive clicks that focus or navigate the application.
- Require explicit permission from the user before they can be displayed.

---

## Basic Usage

To display a native notification, invoke `ctx.show_desktop_notification()` in any async callback:

```python
async def handle_alert(ctx: Context):
    await ctx.show_desktop_notification(
        title="Server Alert",
        body="CPU usage exceeded 90% on server node-42.",
        icon="https://example.com/alert-icon.png",
    )
```

Refast automatically handles the underlying browser's Notification API. The browser will automatically prompt the user for permission when the first notification is triggered, if not already configured.

---

## Live Demo & Event Playground

Configure the fields below to customize a notification payload, and observe how Python handles browser callbacks for permission changes, notification clicks, and close events in real-time.

### Interactive Playground

Configure and fire native notifications to test permission prompts, sounds, and callbacks.

---

## API Reference

### `ctx.show_desktop_notification()`

| Parameter | Type | Default | Description |
|-----------|------|---------|-------------|
| `title` | `str` | *Required* | Bold title displayed at the top of the notification. |
| `body` | `str` | `""` | Subtext/message body of the notification. |
| `icon` | `str \| None` | `None` | URL to a logo or image file displayed within the notification. |
| `tag` | `str \| None` | `None` | Unique string identifier to group notifications. Notifications with the same tag overwrite each other in place. |
| `silent` | `bool` | `False` | When `True`, system audio/vibration cues are disabled. |
| `require_interaction` | `bool` | `False` | When `True`, the notification remains active on screen until dismissed manually. |
| `on_click` | `Callback \| None` | `None` | Fired when the user clicks the notification. Focuses the browser tab automatically. |
| `on_close` | `Callback \| None` | `None` | Fired when the notification is dismissed by the user or closed programmatically. |
| `on_permission_granted` | `Callback \| None` | `None` | Fired immediately if permission is granted when requesting. |
| `on_permission_denied` | `Callback \| None` | `None` | Fired immediately if permission is blocked or denied when requesting. |

---

## Key Concepts & Patterns

### Permission Handling

Operating systems and browsers require the user's explicit consent to show desktop notifications.
- Refast prompts the user for permission automatically when `ctx.show_desktop_notification()` is first called.
- If permission is already granted, it shows the notification immediately.
- If the user blocks notifications, subsequent calls are silently ignored by the OS.
- You can register `on_permission_granted` and `on_permission_denied` callbacks to respond to these choices (e.g., updating UI settings, showing warning banners).

```python
await ctx.show_desktop_notification(
    title="Enable Alerts",
    on_permission_granted=ctx.callback(on_granted),
    on_permission_denied=ctx.callback(on_denied),
)
```

> [!WARNING]
> **Production Latency & User Gesture Blocks**
>
> Modern browsers enforce strict security policies regarding **User Gestures** (transient user activation) for permission prompts like `Notification.requestPermission()`.
>
> Because Refast is a backend-driven framework, callbacks typically execute on the server over WebSockets. In production environments, the network latency (WebSocket hop) can cause the browser to consider the user gesture "expired" by the time the notification command returns. As a result, the browser will block the permission prompt and log a warning in the developer console.
>
> *(Note: This works on `localhost` because browsers bypass or have loose gesture expiration rules for local loops).*

#### Production-Safe Permission Workaround

To ensure that the permission prompt is always triggered within a valid user gesture in production, you should request permission on the client side using a client-side JavaScript callback (`ctx.js`) *before* invoking the backend callback.

You can accomplish this easily using `ctx.chain` to link a client-side JS check with your server-side callback:

```python
Button(
    "Trigger Alert",
    on_click=ctx.chain([
        ctx.js(
            \"""
            if (!('Notification' in window)) {
                alert('This browser does not support desktop notifications.');
            } else if (Notification.permission === 'denied') {
                console.log("[Refast] Notification permission denied");
            } else {
                // Requests permission client-side directly within the user click gesture
                Notification.requestPermission().then(function(p) {
                    console.log("[Refast] Notification permission: " + p);
                });
            }
            \"""
        ),
        ctx.callback(
            trigger_notification,
            props=["notif_title", "notif_body"]
        )
    ])
)
```

Once the user has granted permission on their first click, subsequent clicks will bypass the request phase and display the desktop alert instantly.

### De-duplication using Tags

If you send multiple alerts in a short time frame, they will stack and clutter the user's system notification center. By supplying a stable `tag`, you ensure that a new notification replaces any existing active notification with the same tag in place:

```python
# Updates the progress notification in-place instead of stacking
async def update_progress(ctx: Context, pct: int):
    await ctx.show_desktop_notification(
        title="File Upload",
        body=f"Progress: {pct}% complete",
        tag="upload-progress-alert",
        silent=True, # Prevent sound on every progress increment
    )
```

### Actions on Click

When a user clicks on a desktop notification, the browser automatically focuses the browser window/tab. In the `on_click` Python callback, you can perform additional actions like navigating to a specific route, updating state, or showing a dialog:

```python
async def handle_click(ctx: Context):
    # Focuses and redirects the user's tab to the details page
    await ctx.load("/docs/concepts/desktop-notifications")
    await ctx.show_toast("Redirected from desktop alert!", variant="info")
```

---

## Next Steps

- [Toast Notifications](https://refast.fastapicloud.dev/docs/concepts/toasts) — Inline overlay alerts for immediate feedback
- [Callbacks & Events](https://refast.fastapicloud.dev/docs/concepts/callbacks) — Under the hood of Refast's Python-to-JS events
- [JavaScript Interop](https://refast.fastapicloud.dev/docs/concepts/js-interop) — Advanced scripting for browser controls

---

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).
