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

前端 未结 19 2064
无人共我
无人共我 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

    For a solution without jQuery check out Visibility.js which provides information about three page states

    visible    ... page is visible
    hidden     ... page is not visible
    prerender  ... page is being prerendered by the browser
    

    and also convenience-wrappers for setInterval

    /* Perform action every second if visible */
    Visibility.every(1000, function () {
        action();
    });
    
    /* Perform action every second if visible, every 60 sec if not visible */
    Visibility.every(1000, 60*1000, function () {
        action();
    });
    

    A fallback for older browsers (IE < 10; iOS < 7) is also available

提交回复
热议问题