0

I'm writing a turn-based game in which the server may send messages to the javascript client at random times. When the client receives these messages, it puts an asterisk at the document's title. My problem is, how do I detect that the user is viewing the page, so that I can remove the asterisk as soon as the user has seen the new messages? For instance, how does Gmail and Facebook do it? I heard that one cannot put an onfocus property on the body object.

I would also like to know why the body doens't have the onfocus property.

fonini
  • 2,989
  • 3
  • 21
  • 39
  • `document.hidden` or `document.visibilityState`. [support](http://caniuse.com/#feat=pagevisibility) – Ry- Feb 12 '14 at 21:06

2 Answers2

2

You can check document.hidden, or use document.visibilityState for more options.

Support is pretty good.

Ry-
  • 218,210
  • 55
  • 464
  • 476
  • 2
    Good summary can be seen on https://developer.mozilla.org/en-US/docs/Web/Guide/User_experience/Using_the_Page_Visibility_API – Bart Feb 12 '14 at 21:09
  • I can't get this to work on firefox when I minimize the window. It only triggers when I change tabs. – fonini Feb 13 '14 at 09:18
1

Why not listen for the focus and blur events on window?

window.addEventListener('focus', onFocus); // window has focus
window.addEventListener('blur', onBlur); // window lost focus
posit labs
  • 8,951
  • 4
  • 36
  • 66