Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Determine whether webpage has foreground window focus/is active tab?

I'd like to be able to mute activity of my app if I can detect that the page is no longer focused. For instance, if the page is in a background tab or another app has focus, I'd like to disable a constantly polling script or switch modal notifications to the new HTML5 notifications API.

Is there any way to get this with JS, and if so, which browsers are supported?

PS - I've seen this, but don't know if it would work for what I'm looking to do. Anybody have any insight?

like image 736
mattbasta Avatar asked Jul 16 '10 19:07

mattbasta


People also ask

How do you check if the tab is active?

The Page Visibility API: It lets the developers know if the current tab is currently active or not. When the user switches to another tab or minimizes the window, then the pagevisibilitychange event gets triggered. This API added these properties to the document object.

How do you check if a window is focused?

Use the document. hasFocus() method to check if a window has focus, e.g. if (document. hasFocus()) {} . The method returns a boolean value indicating whether the document or any element in the document has focus.

How to check tab focus in JavaScript?

Use the visibilitychange event to detect if a browser tab has focus or not, e.g. document. addEventListener('visibilitychange', checkTabFocused) . The event is fired at the document when the contents of its tab have become visible or have been hidden.

How do you check if a tab is already open in Javascript?

How do you check if a tab is already open in Javascript? if (+localStorage. tabCount > 0) alert('Already open! '); else localStorage.


1 Answers

You can listen for the blur event on your window, then for when the user comes back, you can use the focus event:

Here's an example in jQuery:

$(window).blur(disableStuff).focus(enableStuff);

Or in pure JavaScript:

window.onblur = disableStuff;
window.onfocus = enableStuff;
like image 94
Jacob Relkin Avatar answered Oct 05 '22 05:10

Jacob Relkin