DetectTab API Documentation
Complete API reference for DetectTab - a comprehensive tab detection and management library for web applications with TypeScript support.
📦 Installation
npm install detect-tab
yarn add detect-tab
pnpm add detect-tab
🚀 Quick Start
import { DetectTab } from 'detect-tab';
// Create instance
const detector = new DetectTab();
// Check current state
console.log('Is visible:', detector.isVisible());
console.log('Is focused:', detector.isFocused());
// Listen for changes
detector.onStateChange((state, info) => {
if (state === 'hidden') {
pauseAnimations();
} else {
resumeAnimations();
}
});
// Listen for focus changes
detector.onFocusChange((focused, info) => {
console.log('Tab focused:', focused);
});
📋 API Reference
Constructor
Creates a new DetectTab instance with optional configuration.
Parameters
Name | Type | Default | Description |
---|---|---|---|
options | DetectTabOptions | {} |
Configuration options for the instance |
DetectTabOptions Interface
Property | Type | Default | Description |
---|---|---|---|
persistent | boolean | false |
Save statistics across browser sessions using localStorage |
debounceTime | number | 100 |
Debounce time for events in milliseconds |
debug | boolean | false |
Enable debug logging to console |
const detector = new DetectTab({
persistent: true, // Save data across sessions
debounceTime: 250, // Wait 250ms before firing events
debug: true // Enable debugging
});
Methods
State Detection Methods
Returns true
if the tab is currently visible, false
otherwise.
Returns true
if the tab is currently focused, false
otherwise.
Returns detailed information about the current tab state and statistics.
Returns formatted time statistics as human-readable strings.
Event Methods
Registers a callback for tab visibility state changes (visible/hidden).
Parameter | Type | Description |
---|---|---|
callback | StateChangeCallback | Function called when state changes: (state: TabState, info: TabInfo) => void |
Registers a callback for tab focus changes (focused/blurred).
Parameter | Type | Description |
---|---|---|
callback | FocusChangeCallback | Function called when focus changes: (focused: boolean, info: TabInfo) => void |
Registers a callback for specific browser events.
Removes a previously registered event callback.
Control Methods
Starts tab detection if it was previously stopped.
Stops tab detection and removes event listeners temporarily.
Resets all statistics and time tracking data.
Permanently destroys the instance and removes all event listeners.
Events
TabEvent Enum
Event | Value | Description |
---|---|---|
VISIBILITY_CHANGE | 'visibilitychange' |
Fired when tab visibility changes |
FOCUS | 'focus' |
Fired when tab gains focus |
BLUR | 'blur' |
Fired when tab loses focus |
STATE_CHANGE | 'statechange' |
Fired when tab state changes |
import { TabEvent } from 'detect-tab';
detector.on(TabEvent.VISIBILITY_CHANGE, (info) => {
console.log('Visibility changed:', info.visible);
});
detector.on(TabEvent.FOCUS, (info) => {
console.log('Tab gained focus');
});
detector.on(TabEvent.BLUR, (info) => {
console.log('Tab lost focus');
});
Types
TabInfo Interface
interface TabInfo {
visible: boolean; // Current visibility state
focused: boolean; // Current focus state
state: TabState; // Current tab state enum
lastStateChange: number; // Timestamp of last state change
visibilityChanges: number; // Total number of visibility changes
focusChanges: number; // Total number of focus changes
timeInCurrentState: string; // Formatted time in current state
totalVisibleTime: number; // Total time visible (milliseconds)
totalHiddenTime: number; // Total time hidden (milliseconds)
}
TimeStats Interface
interface TimeStats {
totalVisibleTime: string; // Formatted total visible time
totalHiddenTime: string; // Formatted total hidden time
timeInCurrentState: string; // Formatted current state time
totalTime: string; // Formatted total session time
}
TabState Enum
enum TabState {
VISIBLE = 'visible',
HIDDEN = 'hidden'
}
💡 Use Cases
Performance Optimization
const detector = new DetectTab();
detector.onStateChange((state) => {
if (state === 'hidden') {
// Pause animations
clearInterval(animationTimer);
// Reduce network requests
clearInterval(dataUpdateTimer);
dataUpdateTimer = setInterval(updateData, 30000); // 30s instead of 1s
// Pause videos
document.querySelectorAll('video').forEach(v => v.pause());
} else {
// Resume normal operations
startAnimations();
clearInterval(dataUpdateTimer);
dataUpdateTimer = setInterval(updateData, 1000); // Back to 1s
document.querySelectorAll('video').forEach(v => v.play());
}
});
Analytics Tracking
detector.onStateChange((state, info) => {
analytics.track('tab_visibility_change', {
visible: info.visible,
timeInState: info.timeInCurrentState,
totalChanges: info.visibilityChanges,
sessionTime: info.totalVisibleTime + info.totalHiddenTime
});
});
// Track session duration on page unload
window.addEventListener('beforeunload', () => {
const stats = detector.getTimeStats();
analytics.track('session_end', {
visibleTime: stats.totalVisibleTime,
hiddenTime: stats.totalHiddenTime,
totalTime: stats.totalTime
});
});
User Experience Enhancement
let notificationCount = 0;
const originalTitle = document.title;
detector.onFocusChange((focused) => {
if (focused) {
// Clear notification badge when user returns
document.title = originalTitle;
notificationCount = 0;
}
});
// Show notification count when hidden
function onNewMessage(message) {
if (!detector.isVisible()) {
notificationCount++;
document.title = `(${notificationCount}) ${originalTitle}`;
// Show browser notification
if (Notification.permission === 'granted') {
new Notification('New Message', {
body: message.text,
icon: '/favicon.ico'
});
}
}
}
🌐 Browser Support
Browser | Version | Visibility API | Focus Detection | Notes |
---|---|---|---|---|
Chrome | 14+ | ✅ | ✅ | Full support |
Firefox | 18+ | ✅ | ✅ | Full support |
Safari | 7+ | ✅ | ✅ | Full support |
Edge | 12+ | ✅ | ✅ | Full support |
IE | 10+ | ⚠️ | ✅ | Limited visibility API |
🔧 Troubleshooting
Common Issues
Events Not Firing
// Enable debug mode to see what's happening
const detector = new DetectTab({ debug: true });
// Check if detection is active
if (!detector.isActive()) {
detector.start();
}
// Verify browser support
if (!document.hidden !== undefined) {
console.warn('Page Visibility API not supported');
}
Memory Leaks
// Always destroy instances when done
window.addEventListener('beforeunload', () => {
detector.destroy();
});
// In React components
useEffect(() => {
const detector = new DetectTab();
return () => {
detector.destroy(); // Cleanup on unmount
};
}, []);
TypeScript Issues
// Import types explicitly
import {
DetectTab,
TabInfo,
TabState,
DetectTabOptions
} from 'detect-tab';
// Use proper typing
const options: DetectTabOptions = {
persistent: true,
debug: false
};
const detector = new DetectTab(options);
requestAnimationFrame
or setTimeout
for expensive operations.
Getting Help
- GitHub Issues: Report bugs or request features
- npm Package: View package details
- Live Demo: Try the interactive demo
Made with ❤️ by meteor314 | MIT License