fonini
fonini

Reputation: 3389

Detect user activity with JavaScript

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.

Upvotes: 0

Views: 347

Answers (2)

posit labs
posit labs

Reputation: 9441

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

Upvotes: 1

Ry-
Ry-

Reputation: 224963

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

Support is pretty good.

Upvotes: 2

Related Questions