Browser State Change Detector

I developed a JavaScript utility to detect and log browser state changes using Page Visibility API and lifecycle events. It tracks states like active, passive, hidden, frozen, and terminated, logging transitions for analytics or debugging. Useful for optimizing performance, user engagement, and resource management in web apps.
Problem / Context
Web apps need to respond to user attention shifts (tab switches, minimization) for efficiency. Without detection, apps waste resources on inactive pages. Needed a reliable way to monitor states and react accordingly.
Constraints / Goals
- Comprehensive: cover all states (active, passive, hidden, frozen, terminated).
- Event-driven: use standard APIs.
- Logging: record changes with timestamps.
- Non-intrusive: passive monitoring.
Core Approach
Listen to events (visibilitychange, focus, blur, etc.), determine state via getState(), log changes if different.
State Determination
const getState = () => {
if (document.visibilityState === "hidden") {
return "hidden";
}
if (document.hasFocus()) {
return "active";
}
return "passive";
};
Logging Changes
let state = getState();
const logStateChange = (nextState) => {
const prevState = state;
if (nextState !== prevState) {
console.log(`State change: ${prevState} >>> ${nextState} - ${new Date().toString()}`);
state = nextState;
}
};
Event Listeners
["pageshow", "focus", "blur", "visibilitychange", "resume"].forEach((type) => {
window.addEventListener(type, () => logStateChange(getState()), { capture: true });
});
window.addEventListener("freeze", () => logStateChange("frozen"), { capture: true });
window.addEventListener("pagehide", (event) => {
logStateChange(event.persisted ? "frozen" : "terminated");
}, { capture: true });
Use Cases
- Analytics: Track user engagement (active time vs passive).
- Performance: Pause animations/videos when hidden.
- Resource Management: Reduce polling in background tabs.
- Notifications: Delay alerts when page is hidden.
- Debugging: Log state transitions for testing.
Results / Impact
- Enables responsive web apps.
- Improves battery life and performance.
- Better user experience.
Trade-offs / Limitations
- Browser-dependent support.
- Not all states in older browsers.
- Passive; doesn’t prevent actions.
Next Steps
- Integrate with analytics libraries.
- Add callbacks for state changes.
- Visualize state history.
Tech Summary
JavaScript, Page Visibility API, lifecycle events.
Summary Pattern Example
Problem: Apps need to detect user attention for optimization.
Approach: Event listeners for state changes via Visibility API.
Result: Comprehensive browser state detector for web performance.