简体   繁体   中英

Distinguish between focus loss inside and outside page?

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 (ie 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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM