I am trying to code my own versions of popular games such as minesweeper, snake 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!
Asked
Active
Viewed 3,527 times
2
-
Possible duplicate: http://stackoverflow.com/questions/1760250/how-to-tell-if-browser-tab-is-active – Chris Laplante Jul 01 '11 at 00:25
-
Thanks for mentioning, it explains how to detect minimized browser, nothing about the tabs switching, so maybe someone will answer here. If not I will delete my post. – Nazar Jul 01 '11 at 00:28
-
You can use the [Page Visibility API](https://developer.mozilla.org/en-US/docs/Web/API/Page_Visibility_API) to detect whether a tab is visible. – Anderson Green May 03 '22 at 14:50
2 Answers
1
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
});
});

sameerali
- 102
- 3
- 12
1
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>

mrk
- 4,999
- 3
- 27
- 42
-
Hi, thanks! That looks pretty simple. What about something like currenttab.onblur even? Does js have something of that sort? – Nazar Jul 01 '11 at 00:39
-
You can only check if your tab has blurred (unless other tabs are from the same domain). If other tabs are from the same domain you would be able to use `window.opener.frames[ index of tab you want to check ].has_blurred` to check a known tab if it blurred. – mrk Jul 01 '11 at 00:54