Sometimes we need to check if the current browser tab is active or not. When you open YouTube and watch a movie for a long in the browser then the auto screen timeout doesn’t work but when you open Facebook, after some time the screen turns off due to the screen timeout of the device. So how does YouTube know if a tab is active?
In this article, we will discuss this. To achieve this functionality we have the following methods.
- The page Visibility API
- Window.onfocus and Window.onblur
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.
- document.hidden: It returns true when the page is not in focus and returns false when the page is in focus.
- document.visibilityState: It returns the current visibility state of the document. It returns these states as “hidden“, “visible”, “unloaded”, and “prerender”. hidden means the current tab is not in focus, visible means the current tab is in focus, unloaded means the current tab is about to close, prerender means the page has been loaded but the user has not viewed the page. It is a read-only property, you cannot modify it.
- document.onvisibilitychange: An eventListener when the visibilitychange event is fired.
Example: In this example, we are creating a popup that gets closed automatically when the user moves to another tab or minimizes the window.
The onfocus/onblur Method: This events are also used to know if the element is visible or not. But there is a problem with this method, If you are opening a small window on top of your current window, then the onblur event gets called, and when you close that small window, the onfocus method does not get called and the window remains in a blur state.
Example: In this example, we are showing a popup that automatically disappears when the user focuses out the current tab.
Output: When the user changes its focus to another window and then again comes back to the original window, it alerts saying the following message.
onfocus event called