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?
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.
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.
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? if (+localStorage. tabCount > 0) alert('Already open! '); else localStorage.
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With