Distinguish between focus loss inside and outside page?

139 Views Asked by At

A <div tabindex="-1"> element might have a focusout listener on it.

The event will fire whenever the focus changes to another element (or nothing) in the page.

However, it will also fire whenever the containing browser tab or window loses focus. This can be caused by a number of things: ALT+TAB, the WINDOWS key, the user mouse-clicking on another application, or the user opening the developer console.

When handling the FocusEvent, is there any way to distinguish between the event being fired due to focus change within the page or outside the page?

As an aside, FocusEvent.relatedTarget is available. However, it seems to be null both when focus goes outside the page and sometimes when it goes to another part inside the page (i.e. an element which cannot 'receive' focus as such). UIEvent.sourceCapabilities also seems to be available, and seems to reliably go null when the page as a whole loses focus, but I'm unsure how reliable this would be for solving this problem.

Any help would be much appreciated.

1

There are 1 best solutions below

0
On

You could use the Page Visibility API to see if the window/tab has user focus

https://developer.mozilla.org/en-US/docs/Web/API/Page_Visibility_API