Skip to content

HTMX 4: Autofocus on Web Awesome components causes swap failure during history restore #3609

@lehoanggiap

Description

@lehoanggiap

Problem

When a Web Awesome component (e.g., <wa-input>) has the autofocus attribute and HTMX restores a page from browser history, HTMX attempts to focus the element before the Web Awesome component is fully registered and initialized. This causes a TypeError: Cannot read properties of null (reading 'focus') error, which aborts the entire swap operation. As a result, htmx:after:swap never fires, preventing HTMX from re-initializing form attributes like hx-put, causing forms to fall back to default browser submission (GET requests).

Important Context: Web Awesome Component Registration

Web Awesome components require time to be defined/registered. According to the Web Awesome documentation on awaiting registration, components need to be awaited before they're fully functional. HTMX's autofocus handling runs before this registration completes, causing the error.

Steps to Reproduce

  1. Create a page with a form containing a Web Awesome input with autofocus and open it in the browser
   <form id="testForm" hx-put="/test">
       <wa-input autofocus id="customer-input" name="name"></wa-input>
   </form>
  1. Navigate to another page
  2. Click browser back button to the test page at step 1
  3. Submit the testForm

Expected: Form submits via HTMX PUT request, data is updated

Actual: Form submits as regular browser form (GET request with query parameters)

Root Cause

HTMX's autofocus handling runs during the swap process (in htmx:before:swap). When it encounters a Web Awesome component with autofocus, it tries to call .focus() on the element. However Web Awesome components need time to register: According to Web Awesome documentation, components must be awaited before they're fully functional

Suggestion

I think we should remove the handleAutoFocus logic during swapping. The code looks for an element with autofocus and explicitly calls focus() on it, which is redundant—elements with autofocus will automatically receive focus without needing an explicit focus() call.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions