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

前端 未结 19 2050
无人共我
无人共我 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 04:43

    There is a neat library available on GitHub:

    https://github.com/serkanyersen/ifvisible.js

    Example:

    // If page is visible right now
    if( ifvisible.now() ){
      // Display pop-up
      openPopUp();
    }
    

    I've tested version 1.0.1 on all browsers I have and can confirm that it works with:

    • IE9, IE10
    • FF 26.0
    • Chrome 34.0

    ... and probably all newer versions.

    Doesn't fully work with:

    • IE8 - always indicate that tab/window is currently active (.now() always returns true for me)

提交回复
热议问题