We regularly run into this Chrome console accessibility warning implementing Bootstrap Modals. There is supposed to be a fix coming in a future release of Bootstrap, but until then, we want to eliminate the warning. Our solution should be adaptable to other packages and components generating the same warning.
Blocked aria-hidden on an element because its descendant retained focus. The focus must not be hidden from assistive technology users. Avoid using aria-hidden on a focused element or its ancestor. Consider using the inert attribute instead, which will also prevent focus. For more details, see the aria-hidden section of the WAI-ARIA specification at https://w3c.github.io/aria/#aria-hidden.
Element with focus: <button.btn-close>
Ancestor with aria-hidden: <div.modal fade#modal>
Toggle “inert” property
Here we toggle the inert
property, as suggested in the warning, with a global event listener.
<script>
window.addEventListener('hide.bs.modal', event => {
event.target.inert = true
})
window.addEventListener('show.bs.modal', event => {
event.target.inert = false
})
</script>
Force blur()
Our initial fix was based on GitHub discussions of the same issue. There are also StackExchange discussions covering the issue, with similar yet overcomplicated solutions.
<script>
window.addEventListener('hide.bs.modal', event => {
document.activeElement.blur()
})
</script>
The document should always have an active element (body if nothing else) so we felt no need to check element type.
Conclusion
We decided toggling inert
was the best solution since calling blur()
might produce unexpected issues for assistive technology users.