JsGuide

Learn JavaScript with practical tutorials and code examples

Code Snippet Intermediate
• Updated Jul 25, 2025

JavaScript Capability Detection Code Snippets

Ready-to-use JavaScript code to detect what JavaScript can do in your environment with feature detection utilities.

JavaScript Capability Detection Code Snippets

These utility functions help you detect what JavaScript can do in different environments. Use these snippets to programmatically determine JavaScript capabilities and adapt your code accordingly.

Browser Capability Detection #

Check What JavaScript Can Do with Web APIs #

Environment-Specific Detection #

// Detect what JavaScript can do in different environments
function detectJavaScriptEnvironment() {
    const environment = {
        // Environment type
        isBrowser: typeof window !== 'undefined',
        isNode: typeof process !== 'undefined' && process.versions && process.versions.node,
        isWebWorker: typeof importScripts !== 'undefined',
        isElectron: typeof process !== 'undefined' && process.versions && process.versions.electron,
        
        // Runtime capabilities
        hasDOM: typeof document !== 'undefined',
        hasConsole: typeof console !== 'undefined',
        hasRequire: typeof require !== 'undefined',
        hasImport: typeof import !== 'undefined',
        
        // Global objects
        hasWindow: typeof window !== 'undefined',
        hasGlobal: typeof global !== 'undefined',
        hasSelf: typeof self !== 'undefined'
    };
    
    // Determine primary environment
    let primaryEnv = 'unknown';
    if (environment.isElectron) primaryEnv = 'electron';
    else if (environment.isNode) primaryEnv = 'node';
    else if (environment.isWebWorker) primaryEnv = 'webworker';
    else if (environment.isBrowser) primaryEnv = 'browser';
    
    return {
        ...environment,
        primaryEnvironment: primaryEnv
    };
}

Feature Support Detection #

Modern JavaScript Features #

API Availability Checker #

// Check what JavaScript can do with various APIs
class APICapabilityChecker {
    static checkWebAPIs() {
        return {
            // Storage APIs
            storage: {
                localStorage: this.isSupported(() => window.localStorage),
                sessionStorage: this.isSupported(() => window.sessionStorage),
                indexedDB: this.isSupported(() => window.indexedDB),
                webSQL: this.isSupported(() => window.openDatabase)
            },
            
            // Communication APIs
            communication: {
                fetch: this.isSupported(() => window.fetch),
                xmlHttpRequest: this.isSupported(() => window.XMLHttpRequest),
                webSocket: this.isSupported(() => window.WebSocket),
                serverSentEvents: this.isSupported(() => window.EventSource)
            },
            
            // Media APIs
            media: {
                getUserMedia: this.isSupported(() => navigator.mediaDevices.getUserMedia),
                webRTC: this.isSupported(() => window.RTCPeerConnection),
                webAudio: this.isSupported(() => window.AudioContext || window.webkitAudioContext),
                fullscreen: this.isSupported(() => document.documentElement.requestFullscreen)
            },
            
            // Device APIs
            device: {
                geolocation: this.isSupported(() => navigator.geolocation),
                deviceMotion: this.isSupported(() => window.DeviceMotionEvent),
                battery: this.isSupported(() => navigator.getBattery),
                vibration: this.isSupported(() => navigator.vibrate)
            },
            
            // Graphics APIs
            graphics: {
                canvas: this.isSupported(() => document.createElement('canvas').getContext('2d')),
                webGL: this.isSupported(() => document.createElement('canvas').getContext('webgl')),
                webGL2: this.isSupported(() => document.createElement('canvas').getContext('webgl2'))
            }
        };
    }
    
    static isSupported(testFunction) {
        try {
            return !!testFunction();
        } catch (e) {
            return false;
        }
    }
    
    static generateCapabilityReport() {
        const capabilities = this.checkWebAPIs();
        let report = "JavaScript Capability Report:\n";
        report += "=" + "=".repeat(30) + "\n\n";
        
        Object.entries(capabilities).forEach(([category, features]) => {
            report += `${category.toUpperCase()}:\n`;
            Object.entries(features).forEach(([feature, supported]) => {
                const status = supported ? "✓" : "✗";
                report += `  ${status} ${feature}\n`;
            });
            report += "\n";
        });
        
        return report;
    }
}

Performance Capability Detection #

Security Capability Detection #

// Check what JavaScript can do regarding security features
function checkSecurityCapabilities() {
    return {
        // Cryptography
        crypto: {
            cryptoAPI: typeof crypto !== 'undefined',
            cryptoSubtle: typeof crypto !== 'undefined' && typeof crypto.subtle !== 'undefined',
            randomValues: typeof crypto !== 'undefined' && typeof crypto.getRandomValues === 'function'
        },
        
        // Content Security
        security: {
            contentSecurityPolicy: typeof CSP !== 'undefined',
            subresourceIntegrity: 'integrity' in document.createElement('script'),
            cors: typeof fetch !== 'undefined', // CORS is handled by fetch
            mixedContent: location.protocol === 'https:'
        },
        
        // Authentication
        auth: {
            webAuthn: typeof PublicKeyCredential !== 'undefined',
            credentialManagement: typeof CredentialsContainer !== 'undefined'
        },
        
        // Permissions
        permissions: {
            permissionsAPI: typeof navigator !== 'undefined' && 'permissions' in navigator,
            notificationPermission: typeof Notification !== 'undefined'
        }
    };
}

Usage Examples #

Adaptive Feature Loading #

Summary #

These capability detection utilities help you:

  • Determine environment capabilities before using specific APIs
  • Implement progressive enhancement based on available features
  • Provide fallbacks for unsupported functionality
  • Optimize performance by using the best available methods
  • Debug compatibility issues across different environments

Use these snippets to build more robust applications that adapt to what JavaScript can do in any given environment, ensuring better user experiences across different browsers and platforms.

Related Snippets

Snippet Intermediate

Fix Async Await Promise Pending - Code Utilities

Ready-to-use JavaScript functions to fix async await promise pending issues with comprehensive error handling and debugging tools.

#javascript #async #await +2
View Code
Syntax
Snippet Intermediate

JavaScript Callback Error Prevention Utilities

Ready-to-use utility functions to fix undefined is not a function error in JavaScript callbacks and prevent callback-related issues.

#javascript #utilities #callbacks +2
View Code
Syntax
Snippet Intermediate

JavaScript Error Handling Code Snippets and Utilities

Ready-to-use JavaScript error handling utilities and code snippets for robust application development and debugging.

#javascript #error #debugging +2
View Code
Syntax
Snippet Intermediate

JavaScript Main Process Error Handler Code Snippets

Ready-to-use JavaScript code snippets for handling main process errors with robust error detection and recovery utilities.

#javascript #error-handling #main-process +2
View Code
Syntax