1

I'd like to track when a certain web-page is (or is not) in the foreground.

I've already experimented with the Page Visibility API, and I can use it to find out if my page is the currently active tab of its window. But I also need to know when my page's window is not in the foreground (despite being the active one of that window).

Is this something I can detect using javascript?

Filipe Correia
  • 5,415
  • 6
  • 32
  • 47

2 Answers2

1

You can use hasFocus event, when it is in foreground (active or not) send to ajax call to server. Here is more info.

Community
  • 1
  • 1
Mustafa Ekici
  • 7,263
  • 9
  • 55
  • 75
1

I use focus and blur events for this, you can do it cross-browser on $(window) with JQuery. Your needs don't appear to require the Page Visibility API, since you only care about if the tab (and window) has actual focus.

Plynx
  • 11,341
  • 3
  • 32
  • 33
  • On my first try it seemed that ``focus`` and ``blur`` events were not reliable, but the "note" on [this answer](http://stackoverflow.com/a/6184276/684253) made it more clear for me what the "pattern" was. I've settled with that solution, which is close to what you were suggesting. I'm using a workaround to the initial focus issue, that involves calling a function (the same function that the focus event handler calls) when the document is ready. – Filipe Correia Jan 15 '13 at 16:53
  • 1
    I'm accepting your answer as it is the closest to what I ended up using, but those looking for a solution should probably check this answer: http://stackoverflow.com/a/6184276/684253 – Filipe Correia Jan 15 '13 at 16:56