3

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.

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.

Any ideas for detecting window visibility? I'm thinking maybe include a tiny Flash "pixel" and detect whether that is visible - any other ideas?

Community
  • 1
  • 1
Michael Kopinsky
  • 884
  • 1
  • 7
  • 14

1 Answers1

13

You can use the Page Visibility API in browsers that support it. Otherwise as you said you will need to use a hack with onfocus/onblur.

visibility.js is 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.

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/

Read: https://developer.mozilla.org/en-US/docs/DOM/Using_the_Page_Visibility_API

Adam
  • 43,763
  • 16
  • 104
  • 144
  • This is great for modern browsers. Unfortunately, my hospital is still stuck on IE7 - in a measurement I did a few weeks ago, 84% of my traffic comes from old IE, 10% Firefox, 7% Chrome. So I will probably use Page visibility to get better stats on the 17% but I guess I'm stuck with onfocus/onblur for the IE users. – Michael Kopinsky Sep 21 '12 at 19:56
  • You can use visibility.js and get all of them – Adam Sep 21 '12 at 20:00
  • Can you convince your users to install Chrome Frame on top of IE? – Adam Sep 21 '12 at 20:02
  • Does visibility.js actually add the functionality to the old browsers? Or does it just degrade invisibly? – Michael Kopinsky Sep 23 '12 at 00:32
  • Encouraging Chrome or Chrome Frame are options, but risk invoking politics with the IT department. Don't want to go there. – Michael Kopinsky Sep 23 '12 at 00:33
  • 2
    if document.hidden is false (not undefined), this code will try document.msHidden etc, and will eventually return undefined, not false for non-mozilla browsers – HelloWorld Aug 31 '16 at 11:33