如何在javascript中检测浏览器最小化和最大化状态

Ash*_*ish 15 javascript

我试图找到浏览器最小化和最大化状态,因为我想相应的浏览器状态点击AJAX请求.

有谁知道如何使用JavaScript检测浏览器状态.

Tob*_*ogh 21

我认为检测这些状态的唯一可靠方法是检查HTML5提供的可见性API(这仍然是一个实验性功能),它提供某些属性和事件

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    
Run Code Online (Sandbox Code Playgroud)

您还可以对可见性的变化做出反应

document.addEventListener("visibilitychange", function() {
  console.log(document.hidden, document.visibilityState);
}, false);
Run Code Online (Sandbox Code Playgroud)

请记住,这不适用于跨浏览器,仅适用于某些浏览器版本.

  • @DavidCallanan 这是一个不同的属性,称为焦点。检查“document.hasFocus()”和“window”的“focus”事件。 (2认同)

小智 6

我用这个代码

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

window.addEventListener('focus', function(){
   console.log('focus');
}, false);
Run Code Online (Sandbox Code Playgroud)


小智 5

这是Piotrek De对另一个问题的回答:

GitHub 上有一个简洁的库:

https://github.com/serkanyersen/ifvisible.js

例子:

// If page is visible right now
if( ifvisible.now() ){
  // Display pop-up
  openPopUp();
}
Run Code Online (Sandbox Code Playgroud)

我已经在我拥有的所有浏览器上测试了版本 1.0.1,并且可以确认它适用于:

  • IE9、IE10
  • FF 26.0
  • 铬34.0

可能还有所有较新的版本。

不完全适用于:

  • IE8 - 始终指示选项卡/窗口当前处于活动状态(.now() 始终为我返回 true )


zvo*_*ona 2

您可以尝试使用Page Visibility API,它具有布尔属性document.hidden(document.webkitHidden),它还可以检测当前页面是最小化还是最大化。它还取决于用户是否聚焦当前浏览器选项卡:

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

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