Is there a way to detect if a browser window is not currently active?

前端 未结 19 1936
无人共我
无人共我 2020-11-21 04:40

I have JavaScript that is doing activity periodically. When the user is not looking at the site (i.e., the window or tab does not have focus), it\'d be nice to not run.

19条回答
  •  南笙
    南笙 (楼主)
    2020-11-21 05:01

    This is really tricky. There seems to be no solution given the following requirements.

    • The page includes iframes that you have no control over
    • You want to track visibility state change regardless of the change being triggered by a TAB change (ctrl+tab) or a window change (alt+tab)

    This happens because:

    • The page Visibility API can reliably tell you of a tab change (even with iframes), but it can't tell you when the user changes windows.
    • Listening to window blur/focus events can detect alt+tabs and ctrl+tabs, as long as the iframe doesn't have focus.

    Given these restrictions, it is possible to implement a solution that combines - The page Visibility API - window blur/focus - document.activeElement

    That is able to:

    • 1) ctrl+tab when parent page has focus: YES
    • 2) ctrl+tab when iframe has focus: YES
    • 3) alt+tab when parent page has focus: YES
    • 4) alt+tab when iframe has focus: NO <-- bummer

    When the iframe has focus, your blur/focus events don't get invoked at all, and the page Visibility API won't trigger on alt+tab.

    I built upon @AndyE's solution and implemented this (almost good) solution here: https://dl.dropboxusercontent.com/u/2683925/estante-components/visibility_test1.html (sorry, I had some trouble with JSFiddle).

    This is also available on Github: https://github.com/qmagico/estante-components

    This works on chrome/chromium. It kind works on firefox, except that it doesn't load the iframe contents (any idea why?)

    Anyway, to resolve the last problem (4), the only way you can do that is to listen for blur/focus events on the iframe. If you have some control over the iframes, you can use the postMessage API to do that.

    https://dl.dropboxusercontent.com/u/2683925/estante-components/visibility_test2.html

    I still haven't tested this with enough browsers. If you can find more info about where this doesn't work, please let me know in the comments below.

提交回复
热议问题