There may be situations when we need to check if a browser tab is focused or not. The reasons for this include:
- Prevent sending network requests if the page is not being used by the user as this would reduce the amount of load on the server. Also, this would save upon the cost if we are using a paid third-party API.
- Stop playback of media when the tab is not focused.
- Automatically pause an in-browser game when the user switches to another window or tab.
- Many sites track the time period for which the user was actually interacting with the website using this functionality.
In this article, we will learn how to implement this functionality. We have the following two methods:
Using the Page Visibility API: HTML5 provides the Page Visibility API that lets the developer know if the tab is currently visible or not. The API sends a visibilitychange event when the user minimizes the window or switches to another tab. This API adds the following two properties to the document object and both properties are read-only.
The document.hidden property: This property returns false when the current tab is ‘visible’, else returns true. The visible keyword has a special meaning here. Suppose you open another small window on top of the current tab, the document.hidden would return false even though the tab isn’t in focus because the rest of the tab is still visible which is not covered by the small window.
The document.visibilityState property: This property returns a string indicating the document’s current visibility state. Possible values are:
- visible: The page content is visible or at least partially visible as explained above.
- hidden: The page content is not visible to the user, either due to the document’s tab being in the background or part of a window that is minimized, or because the device’s screen is off.
- prerender: The page has been loaded but the user has not viewed the page.
- unloaded: The page is in the process of being unloaded from memory i.e. it is about to be closed.
Example: We will create a webpage that would change the color when the user switches tab or minimizes the window.
Using the window.onfocus and Window.onblur events:
- window.onfocus: This event gets fired when the tab has received focus.
- window.onblur: The blur event fires when the user minimizes the window, switches to another tab, or uses another window. The blur event gets fired even when we use another small window and the tab is still partially visible or even when we click on the location bar of the browser.
Example: We will create a webpage that would change the color when the tab looses focus. Here we will try to switch to another window and understand the difference between document.hidden and window.onblur.