Saturday, 26 March 2022

How to pass focus from an iframe to next focusable element in host page?

Background

I have an iframe widget which will be embedded in other pages - I have no prior knowledge of the host page's structure and code, and the iframe will be cross-domain and likely sandboxed.

My goal is to give the iframe widget a single tab stop - after focusing on it there's a dedicated key combination to "enter" the widget, but normal tabbing should skip forward to the next focusable element in the host page.

Question: After the iframe receives focus and a new tab keypress is detected, how can I pass the focus to the host page's next focusable element?

Simple example:

<!-- host page -->
<button> first button </button>
<iframe src="myIframeWidget.com"/>
<button> second button </button>

In the above, if the first button is focused, then the expected behavior is that on first tab the iframe will receive focus, and on the next tab the second button will receive focus (skipping all focusable elements inside the iframe).

Once the iframe is focused and tab is pressed, I need to pass the focus from my iframe to the second button.

Notes

  1. Since my iframe DOM is rather large, I don't want to set tabindex=-1 to all internal focusable elements.
  2. At the time of writing, aria-hidden="true" does not remove an element or its descendants from the focus sequence. I'm not aware of any other aria attribute which removes an entire subtree from the focus sequence.
  3. A pure JS solution is preferred to one relaying on external packages.
  4. I'll also need to handle reverse-tabbing, but I assume that the same approach for forward-tabbing will apply - if there are any crucial differences, please mention them in your answer if possible.
  5. There's an edge case where there isn't anything focusable after the widget - typically in those cases the browser will focus on the address bar buttons - if there's a way to handle that it'll be great to know, but this probably should be handled in a separate question.

Thanks!



from How to pass focus from an iframe to next focusable element in host page?

No comments:

Post a Comment