Safe target — auto-add hx-target="this" to event-driven elements.
When hx-boost sets hx-target on the
, that target propagates to every child element via htmx's attribute inheritance. Self-updating elements (counters, badges, live regions) that usehx-triggerwith
from:to listen for server-sent events inherit this global target
and silently swap their tiny fragment response into the main content
area, wiping the page.
This script fixes the footgun automatically. On everyhtmx.onLoadcallback
(htmx 2 load and htmx 4htmx:after:process), it finds elements that:
- Listen for events from elsewhere (
hx-triggercontainsfrom:) - Make an HTTP request (
hx-get,hx-post, etc.) - Have no explicit
hx-target
…and addshx-target="this"so the response targets the element
itself instead of the inherited layout target.
The attribute is visible in DevTools — it looks like the developer
wrote it. If a developer setshx-targetexplicitly, the
:not([hx-target])selector skips the element.
Injected into every full-page HTML response viaHTMLInject
middleware. Disabled withAppConfig(safe_target=False).
server.htmx_safe_target
| Name | Type | Default | Description |
|---|---|---|---|
type
|
|
— | |
qualified_name
|
|
— | |
element_type
|
|
— | |
description
|
|
— | |
source_file
|
|
— | |
line_number
|
|
— | |
is_autodoc
|
|
— | |
autodoc_element
|
|
— | |
_autodoc_template
|
|
— | |
_autodoc_url_path
|
|
— | |
_autodoc_page_type
|
|
— | |
title
|
|
— | |
doc_content_hash
|
|
— |
Symbols on this page
safe_target_snippet
function
def safe_target_snippet(nonce: str = '') -> str
Build the safe-target inline<script>.
When nonce is non-empty the<script> carries a nonce="..."
attribute so it survives a nonce-based CSP that no longer ships
'unsafe-inline'.
Parameters
| Name | Type | Default | Description |
|---|---|---|---|
nonce
|
str
|
''
|
View source · /home/runner/work/chirp/chirp/site/../src/chirp/server/htmx_safe_target.py:1