Bug 236585

Summary: Safari moves focus to first focusable element inside an element with role="dialog" and aria-modal="true" when added to the DOM
Product: WebKit Reporter: Alex Moore <matthew.garrath.thomas>
Component: AccessibilityAssignee: Nobody <webkit-unassigned>
Status: NEW ---    
Severity: Normal CC: andresg_22, ntim, tyler_w, webkit-bug-importer
Priority: P2 Keywords: InRadar
Version: Safari 15   
Hardware: All   
OS: iOS 15   
Attachments:
Description Flags
Test Case
none
Crash message after inspect none

Description Alex Moore 2022-02-14 03:51:58 PST
Created attachment 451883 [details]
Test Case

All Platforms - iOS (15.3) and MacOS 

Adding an element with the attributes role="dialog" and aria-modal="true" containing focusable elements causes the first of these elements to receive focus. This is not the behaviour of Firefox or Chrome, and causes compatibility issues. 

Related bugs (possibly over-specific): https://bugs.webkit.org/show_bug.cgi?id=211934

See the test case. Reproduce by clicking the button to add the element with role="dialog" and aria-modal to the DOM. See the button inside the element receive focus.
Comment 1 Radar WebKit Bug Importer 2022-02-14 03:52:09 PST
<rdar://problem/88897436>
Comment 2 Tyler Wilcock 2022-05-05 17:21:24 PDT
Thanks for the bug report!

It's implemented this way due to this language in the aria-modal spec (though WebKit's autofocus behavior will currently also apply to <dialog>):

https://w3c.github.io/aria/#aria-modal

> When a modal element is displayed, assistive technologies SHOULD navigate to the element unless focus has explicitly been set elsewhere.

Technically, with that wording it should be VoiceOver (and other assistive technologies) doing this automatic focusing, but WebKit does this itself for now.

I do understand how this could be annoying when other browsers don't do this. And it would definitely be a bug if this autofocus behavior is trouncing explicit focus via JS or otherwise.
Comment 3 Alex Moore 2022-05-10 05:16:52 PDT
It seems that the focus isn't moved anymore in either Safari TP or iOS 15.5 beta, so something must have changed the behaviour, as it now matches the other browsers. 

It might be due to another bug though, as Safari TP seems to struggle with the page, and it crashes and then needs to reload it as soon as you try to inspect it. See the attached screenshot.
Comment 4 Alex Moore 2022-05-10 05:17:49 PDT
Created attachment 459109 [details]
Crash message after inspect

Crash message after inspect
Comment 5 Alex Moore 2022-05-10 05:36:15 PDT
Edit: Only changed in Safari TP, not iOS.
Comment 6 Tyler Wilcock 2022-05-13 09:36:45 PDT
The crash you're experiencing will be fixed by https://bugs.webkit.org/show_bug.cgi?id=240365 (Infinite recursion caused by call to accessibilityIsIgnored in the midst of AccessibilityObject::ignoredFromModalPresence). With this change in place, I can confirm that the latest `main` WebKit does still autofocus with your testcase.