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

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?


Solution 1:

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.

Solution 2:

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)