DetectTab API Documentation

Complete API reference for DetectTab - a comprehensive tab detection and management library for web applications with TypeScript support.

📚 Note: This documentation covers the complete API. For interactive examples, visit the live demo page.

📦 Installation

npm
npm install detect-tab
yarn
yarn add detect-tab
pnpm
pnpm add detect-tab

🚀 Quick Start

Basic Usage
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

new DetectTab(options?: DetectTabOptions)

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
Constructor Example
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

isVisible(): boolean

Returns true if the tab is currently visible, false otherwise.

isFocused(): boolean

Returns true if the tab is currently focused, false otherwise.

getTabInfo(): TabInfo

Returns detailed information about the current tab state and statistics.

getTimeStats(): TimeStats

Returns formatted time statistics as human-readable strings.

Event Methods

onStateChange(callback: StateChangeCallback): void

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
onFocusChange(callback: FocusChangeCallback): 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
on(event: TabEvent, callback: Function): void

Registers a callback for specific browser events.

off(event: TabEvent, callback: Function): void

Removes a previously registered event callback.

Control Methods

start(): void

Starts tab detection if it was previously stopped.

stop(): void

Stops tab detection and removes event listeners temporarily.

reset(): void

Resets all statistics and time tracking data.

destroy(): void

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
Event Usage
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

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

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

TabState Enum
enum TabState {
    VISIBLE = 'visible',
    HIDDEN = 'hidden'
}

💡 Use Cases

Performance Optimization

Pause Expensive Operations
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

Track User Engagement
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

Smart Notifications
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
📱 Mobile Support: DetectTab works on mobile browsers including iOS Safari and Android Chrome with proper handling of mobile-specific behaviors like app switching.

🔧 Troubleshooting

Common Issues

Events Not Firing

Debug Events
// 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

Proper Cleanup
// 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

Type Safety
// 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);
⚠️ Performance Warning: Avoid heavy operations in event callbacks as they can block the main thread. Use requestAnimationFrame or setTimeout for expensive operations.

Getting Help


Made with ❤️ by meteor314 | MIT License