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?
While searching about this problem, I found a recommendation that Page Visibility API should be used. Most modern browsers support this API according to Can I Use: http://caniuse.com/#feat=pagevisibility.
Here's a working example (derived from this snippet):
Update: The example above used to have prefixed properties for Gecko and WebKit browsers, but I removed that implementation because these browsers have been offering Page Visibility API without a prefix for a while now. I kept Microsoft specific prefix in order to stay compatible with IE10.
Yes,
window.onfocus
andwindow.onblur
should work for your scenario:http://www.thefutureoftheweb.com/blog/detect-browser-window-focus
Fun & Easy to Use!
The following plugin will go through your standard test for various versions of IE, Chrome, Firefox, Safari, etc.. and establish your declared methods accordingly. It also deals with issues such as:
Use is as simple as: Scroll Down to 'Run Snippet'
I would do it this way (Reference http://www.w3.org/TR/page-visibility/):
Surprising to see nobody mentioned
document.hasFocus
MDN has more information.
Important Edit: This answer is outdated. Since writing it, the Visibility API (mdn, example, spec) has been introduced. It is the better way to solve this problem.
AFAIK,
focus
andblur
are all supported on...everything. (see http://www.quirksmode.org/dom/events/index.html )