javascriptoptimizationpolling

Detect If Browser Tab Has Focus


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?


Solution

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