Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to detect browser "minimized" and "maximized" state in JavaScript? [duplicate]

Tags:

javascript

I am trying to find the browser minimized and maximized states, as I want to hit the AJAX request accordingly the browser state.

Does anyone know how do I detect the browser state using JavaScript?

like image 310
Ashish Avatar asked Apr 26 '12 07:04

Ashish


4 Answers

I think the only reliable way to detect these states is to check the visibility API offered by HTML5 (this is still an experimental feature) which offers certain properties and events

document.hidden // Returns true if the page is in a state considered to be hidden to the user, and false otherwise.

document.visibilityState // Returns a string denoting the visibility state of the document    

You can also react on changes of the visibility

document.addEventListener("visibilitychange", function() {
  console.log(document.hidden, document.visibilityState);
}, false);

Keep in mind this is not working cross browser and only available in certain browser versions.

like image 191
Tobias Krogh Avatar answered Oct 19 '22 18:10

Tobias Krogh


I use this code

window.addEventListener('blur', function(){
   console.log('blur');
}, false);

window.addEventListener('focus', function(){
   console.log('focus');
}, false);
like image 25
Justan Avatar answered Oct 19 '22 18:10

Justan


Here's Piotrek De's answer on another question:

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)
like image 5
user1089766 Avatar answered Oct 19 '22 19:10

user1089766


You can try with Page Visibility API, it has the boolean property document.hidden (document.webkitHidden), which also detects whether current page is minimized or maximized. It is also dependant whether user has focused current browser tab or not:

https://developers.google.com/chrome/whitepapers/pagevisibility

https://developer.mozilla.org/en/DOM/Using_the_Page_Visibility_API

like image 2
Samuli Hakoniemi Avatar answered Oct 19 '22 19:10

Samuli Hakoniemi