javascript 检测窗口是否可见
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12536562/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Detect whether a window is visible
提问by Michael Kopinsky
Possible Duplicate:
Javascript: Is there any way to detect that window is currently active? (i.e. is beening shown on active tab/window)
I have a web-based dashboard which displays critical time-sensitive messages to nurses etc. on a hospital floor. The challenge is that if the dashboard is not open or is minimized, they will not see the message and be able to respond. I currently track percent of time that the app is running (it polls for new messages over AJAX every 10 seconds so I can easily see how many requests it does per hour or whatever), but that doesn't tell me whether the app was minimized.
我有一个基于 Web 的仪表板,可以向医院楼层的护士等显示关键的时间敏感消息。挑战在于,如果仪表板未打开或最小化,他们将看不到消息并能够做出响应。我目前跟踪应用程序运行的时间百分比(它每 10 秒通过 AJAX 轮询新消息,因此我可以轻松查看它每小时执行多少请求或其他),但这并不能告诉我应用程序是否已最小化.
One method would be to use onfocus
/onblur
, but that has limited effectiveness since most of the computers where this is deployed are dual-monitor machines and they often will keep the dashboard open on one screen while using the Clinical Information System on the other screen. This state will count as "unfocused" with the focus/blur method, but I want it to count as "open" for my stats.
一种方法是使用onfocus
/ onblur
,但这种方法的有效性有限,因为部署此方法的大多数计算机都是双显示器机器,它们通常会在一个屏幕上保持仪表板打开,同时在另一个屏幕上使用临床信息系统。使用焦点/模糊方法,此状态将计为“未聚焦”,但我希望将其计为我的统计数据的“打开”。
Any ideas for detecting window visibility? I'm thinking maybe include a tiny Flash "pixel" and detect whether that is visible - any other ideas?
检测窗口可见性的任何想法?我在想可能包含一个微小的 Flash“像素”并检测它是否可见 - 还有其他想法吗?
回答by Adam
You can use the Page Visibility APIin browsers that support it. Otherwise as you said you will need to use a hack with onfocus/onblur.
您可以在支持它的浏览器中使用页面可见性 API。否则,正如您所说,您将需要使用 onfocus/onblur 进行黑客攻击。
visibility.jsis a library that abstracts this across all browsers. It will use the onblur/onfocus hack if the browser does not support the Page Visibility API.
visibility.js是一个在所有浏览器中抽象它的库。如果浏览器不支持页面可见性 API,它将使用 onblur/onfocus hack。
function isPageHidden(){
return document.hidden || document.msHidden || document.webkitHidden || document.mozHidden;
}
Source: http://www.nczonline.net/blog/2011/08/09/introduction-to-the-page-visibility-api/
来源:http: //www.nczonline.net/blog/2011/08/09/introduction-to-the-page-visibility-api/
Read: https://developer.mozilla.org/en-US/docs/DOM/Using_the_Page_Visibility_API
阅读:https: //developer.mozilla.org/en-US/docs/DOM/Using_the_Page_Visibility_API