Detect If Browser Tab Has Focus

Fenton picture Fenton · Sep 12, 2011 · Viewed 131.7k times · Source

Is there a reliable cross-browser way to detect that a tab has focus.

The scenario is that we have an application that polls regularly for stock prices, and if the page doesn't have focus we could stop the polling and save everyone the traffic noise, especially as people are fans of opening several tabs with different portfolios.

Is window.onblur and window.onfocus an option for this?

Answer

Ryan Wright picture Ryan Wright · Sep 12, 2011

Yes, window.onfocus and window.onblur should work for your scenario:

http://www.thefutureoftheweb.com/blog/detect-browser-window-focus