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?
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.
I use this code
window.addEventListener('blur', function(){
console.log('blur');
}, false);
window.addEventListener('focus', function(){
console.log('focus');
}, false);
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)
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With