How to Check if a Window or Browser Tab Has Focus in JavaScript
When building interactive web applications, you often need to know if the user is actively looking at your page. This is crucial for tasks like pausing a game or video when the user switches away, or for re-fetching data when they return. However, "having focus" can mean two different things:
- Is the browser window itself the active window on the user's desktop?
- Is your page the active tab within the browser?
This guide will teach you the modern, standard methods for answering both of these questions using document.hasFocus() and the Page Visibility API.
The Two Types of "Focus": Window vs. Tab
It's essential to understand the difference between these two states to choose the right tool for your needs.
- Window Focus: Refers to whether the browser window is the active application on the user's operating system.
document.hasFocus()answers this. - Tab Visibility: Refers to whether your page is the currently selected tab in a non-minimized browser window.
document.visibilityStateanswers this.
A page can be the active tab (visibilityState is visible) but the window can still lose focus (hasFocus() is false) if the user clicks on another application.
Solution 1: Check if the Browser Window Has Focus (document.hasFocus())
The document.hasFocus() method is a simple function that returns a boolean.
The syntax:
document.hasFocus()
- Returns
trueif the document (or any element within it) has focus. - Returns
falseif the user has clicked on another application window.
This example uses setInterval to check the window's focus every second.
const statusDiv = document.getElementById('status');
setInterval(() => {
if (document.hasFocus()) {
statusDiv.textContent = '✅ Window has focus';
document.body.style.backgroundColor = 'lightgreen';
} else {
statusDiv.textContent = '⛔️ Window does NOT have focus';
document.body.style.backgroundColor = 'lightcoral';
}
}, 1000);
This is useful for detecting if the user has switched away from the browser entirely.
Solution 2 (Recommended): Check if the Tab is Visible (Page Visibility API)
For most use cases, what you really want to know is if your tab is visible. The Page Visibility API is the modern and recommended standard for this. It is more efficient than polling with setInterval because it uses events.
The API provides two key parts:
document.visibilityState: A property that returns a string:'visible': The page is the foreground tab of a non-minimized window.'hidden': The page is a background tab or part of a minimized window.
visibilitychangeevent: An event that fires on thedocumentwhenever thevisibilityStatechanges.
This is the best practice for detecting when a user leaves and returns to your tab.
const statusDiv = document.getElementById('status');
function handleVisibilityChange() {
if (document.visibilityState === 'visible') {
statusDiv.textContent = '✅ Tab is active and visible';
document.body.style.backgroundColor = 'lightgreen';
} else {
statusDiv.textContent = '⛔️ Tab is hidden or minimized';
document.body.style.backgroundColor = 'lightcoral';
}
}
// Listen for the event
document.addEventListener('visibilitychange', handleVisibilityChange);
// Run the check once on page load as well
handleVisibilityChange();
This event-driven approach is highly efficient as your code only runs when the state actually changes.
How the Methods Work and Their Key Differences
document.hasFocus(): This method directly queries the browser's window manager to see if it is the active window on the user's desktop. It does not have a corresponding event, so you must poll it withsetIntervalto track changes.- Page Visibility API: This is a modern browser API designed specifically to solve the problem of knowing when content is visible. It is more efficient because the browser itself tells you when the state changes via the
visibilitychangeevent. This is the recommended method for pausing/resuming activity, as a hidden tab is the most common way for a page to become inactive.
Conclusion
Determining if your page is active is crucial for creating a responsive and resource-efficient web application.
The key takeaways are:
- To check if the browser window is the active application on the desktop, use
document.hasFocus(). You will need to poll this withsetIntervalto detect changes. - To check if your page is the visible tab, the Page Visibility API is the recommended best practice.
- Check the current state with the
document.visibilityStateproperty. - Listen for changes with the
visibilitychangeevent for an efficient, event-driven approach.
- Check the current state with the