Focus is left on an input inside a closed dialog

#41284677 Area: Blink>DOM / focus CL 8644932 In Review

What happens

Closing a dialog restores focus to whatever was focused when it opened. If nothing was focused -- the reporter's case was a page loaded with focus still in the browser UI, then a dialog with an autofocused input -- there is nothing to restore, and HTMLDialogElement::CloseDialog() simply left document.activeElement on the node inside the dialog that is now closed and no longer focusable.

The visible symptom from the 2016 report: keydown / keyup listeners on the document stop firing, so a barcode scanner typing into the page goes nowhere, and even a reload does not help until the page is refocused from the browser UI.

The close steps in the HTML spec only say what to do when there is a previously focused element; the CL fills in the missing else branch by clearing the focused element when focus is still inside the dialog.

showModal() with nothing focused, focus an input, close()

Your browser: unpatched Chrome reports the input as the active element after the dialog is gone.
Before: activeElement is the input
Without the patch: document.activeElement is <input id=field>, inside the closed dialog.
After: activeElement is body
With the patch: focus falls back to the body and document key events keep working.
Diff mask over the readout
1077 px differ -- the two readout rows.

The change

The restore and the new fallback are the two halves of one decision, so they are now a single if/else instead of two separate passes over previously_focused_element_ -- the second of which used to run even right after the first had restored focus.

A WPT, the-dialog-element/dialog-close-focus-no-previous.html, asserts that document.activeElement is the body after the close; it fails on a build without the fix.

Verification

Links

Issue 41284677 CL 8644932 standalone sampler.html capture_screenshots.py