The title explains itself. How can I detect if a web page has gone to background?
I’m implementing a chat application and I’ll use this information to decide showing new message notifications. I suppose that GMail uses something like that. If the page is on background, it shows desktop notifications (on chrome), if not it doesn’t show them.
I know that the answer has already been selected but I wanted to share another way.
You can use the
hasFocusmethod on thedocumentto see if it has the focus. There is no reason to set your own variable.Here’s some proof of concept code. jsFiddle is at the bottom. Every 3 seconds it will check if the window has focus or not–displaying true or false.
HTML:
CSS:
Javascript inside on document ready:
http://jsfiddle.net/natedavisolds/2D7za/1/