Yes, the browser provides the Page Visibility API and the focus/blur events on the window object to determine if a page has focus. Here's how to use them:
1. Page Visibility API (Best for Tab Switching)
Detect if the page is visible/hidden (e.g., user switches tabs, minimizes window).
javascript
// Check current state
console.log("Page visible?", !document.hidden);
console.log("Visibility state:", document.visibilityState);
// Listen for changes
document.addEventListener('visibilitychange', () => {
if (document.visibilityState === 'visible') {
console.log('Page is visible (has focus)');
} else {
console.log('Page is hidden (lost focus)');
}
});
document.hidden: true if the page is not visible.
document.visibilityState: Returns 'visible' or 'hidden'.
2. window.focus and window.blur Events (Best for Window Focus)
Detect when the entire browser window gains/loses focus (e.g., switching apps).
javascript
window.addEventListener('focus', () => {
console.log('Window has focus');
});
window.addEventListener('blur', () => {
console.log('Window lost focus');
});
Key Differences:
Scenario
Page Visibility API
window focus/blur
User switches browser tabs
✅ Detects
❌ Fails
User minimizes window
✅ Detects
✅ Detects
User switches to another app
❌ Fails
✅ Detects
Page loads in a background tab
✅ Correctly "hidden"
✅ Initially "blurred"
Recommendation:
Use Page Visibility API for tab-switching scenarios (e.g., pause video when tab is backgrounded).
Use window focus/blur for window-level focus (e.g., pause game when user switches apps).