开发者

Detect the browser tab switching/ browser minimising using javascript

I am trying to code my own versions of popular games such as minesweeper, s开发者_如何转开发nake etc using JavaScript. Some of the games require timer, so I wonder is it possible to detect whether user switched to another tab or minimized the browser so I can put the game on pause mode? Thanks for any help provided!


You could set a var when the window catches the onblur event.

<script>
var has_blurred = 0;
function meep()
{
    has_blurred = 1;
    game.pause();
}
window.onblur=meep;
</script>

EDIT adding onfocus

Then later on in the same window/tab, you can handle if your window/tab has ever blurred with an onfocus handler.

<script>
function handleFocus()
{
    if( has_blurred )
        game.unpause();              
    has_blurred = 0; // reset has_blurred state
}
window.onfocus=handleFocus;
</script>


You can do with this code

$(document).ready(function(){
  $([window, document]).focusin(function(){
  //Your logic when the page gets active
   }).focusout(function(){
  //Your logic when the page gets inactive
 });
});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜