Modern Web APIs

HTML5 APIs Overview

Explore the powerful HTML5 APIs that enable modern web applications. From geolocation and storage to notifications and WebRTC - discover what's possible in today's browsers.

What are the HTML5 APIs?

"HTML5 APIs" is the common name for the JavaScript interfaces browsers provide alongside HTML: Web Storage (localStorage), IndexedDB, Geolocation, Drag and Drop, Canvas, Web Workers, WebSockets, Server-Sent Events, Notifications, the History API, Fetch and Service Workers. They let web apps store data, work offline, run background tasks and talk to servers in real time.

HTML5 API Categories

Location & Device

  • Geolocation API
  • Device Orientation
  • Battery Status
  • Network Information

Storage & Data

  • Web Storage API
  • IndexedDB
  • File API
  • Cache API

Communication

  • Fetch API
  • WebSockets
  • Server-Sent Events
  • WebRTC

Media & Graphics

  • Canvas API
  • WebRTC Camera
  • Web Audio API
  • MediaDevices

User Interface

  • Notifications API
  • Fullscreen API
  • Page Visibility
  • History API

Performance

  • Web Workers
  • Performance API
  • Intersection Observer
  • Mutation Observer

Browser Support & Feature Detection

HTML5 APIs have varying levels of browser support. Always use feature detection to ensure your applications work across different browsers and provide appropriate fallbacks.

Feature Detection Best Practices

  • Check for API availability before use
  • Provide meaningful fallbacks
  • Test across different browsers
  • Use progressive enhancement
  • Handle permissions gracefully
  • Inform users about requirements
  • Consider mobile limitations
  • Monitor browser compatibility

Essential HTML5 APIs Deep Dive

Geolocation API

The Geolocation API provides access to the user's geographical location through GPS, WiFi networks, cell towers, and IP addresses. It requires explicit user permission and works across all modern browsers.

Core Methods

  • getCurrentPosition() - Get current location once
  • watchPosition() - Monitor location changes
  • clearWatch() - Stop watching position

Position Options

  • enableHighAccuracy: Use GPS for better precision
  • timeout: Maximum time to get position
  • maximumAge: Accept cached position age

Use Cases

  • • Location-based services and recommendations
  • • Maps and navigation applications
  • • Weather and local information
  • • Delivery and ride-sharing apps

Web Storage API

Web Storage provides a way to store data locally within the user's browser with a much larger storage capacity than cookies. It includes localStorage for persistent storage and sessionStorage for session-based storage.

Storage Types

localStorage: Persists until explicitly cleared
sessionStorage: Cleared when tab closes

Storage Limits

  • • Capacity: ~5-10MB per origin
  • • Data Type: Strings only (use JSON)
  • • Synchronous: Blocking operations

Best Practices

  • • Always check for storage availability
  • • Handle quota exceeded errors
  • • Use JSON for complex data
  • • Consider performance for large data

Web Workers API

Web Workers enable running JavaScript in background threads, preventing UI blocking during CPU-intensive operations. They communicate with the main thread through message passing.

Worker Types

  • Dedicated Workers: One-to-one with main thread
  • Shared Workers: Shared across multiple contexts
  • Service Workers: For offline functionality

Communication

  • postMessage() - Send data to worker
  • onmessage - Receive data from worker
  • terminate() - Stop worker execution

Ideal Use Cases

  • • Image/video processing
  • • Data parsing and transformation
  • • Cryptographic operations
  • • Real-time data analysis

Notifications API

The Notifications API allows web applications to display system notifications to users, even when the browser tab is not active. It requires user permission and supports rich notification content.

Permission States

  • default: User hasn't made a choice
  • granted: User has allowed notifications
  • denied: User has blocked notifications

Notification Options

  • title: Notification headline
  • body: Main notification text
  • icon: Image to display
  • tag: Unique identifier for grouping

Event Handling

  • onclick - User clicks notification
  • onshow - Notification displayed
  • onclose - Notification closed
  • onerror - Error occurred

Advanced Communication APIs

WebSockets API

WebSockets provide full-duplex communication channels over a single TCP connection, enabling real-time data exchange between client and server with minimal overhead.

Connection States

  • CONNECTING (0): Connection establishing
  • OPEN (1): Connection ready for data
  • CLOSING (2): Connection closing
  • CLOSED (3): Connection closed

Key Advantages

  • • Low latency real-time communication
  • • Bidirectional data flow
  • • Reduced server overhead
  • • Support for binary data

Common Applications

  • • Chat and messaging systems
  • • Live gaming and multiplayer
  • • Real-time collaboration tools
  • • Live data feeds and trading

Server-Sent Events (SSE)

Server-Sent Events provide a standardized way for servers to push data to web pages over HTTP. Unlike WebSockets, SSE is unidirectional from server to client.

EventSource Events

  • onopen - Connection established
  • onmessage - Data received
  • onerror - Connection error
  • close() - Close connection

SSE vs WebSockets

  • SSE: Simpler, HTTP-based, server-to-client
  • WebSockets: Bidirectional, more complex
  • SSE: Automatic reconnection
  • WebSockets: Lower latency

Perfect For

  • • Live news feeds and updates
  • • Stock price streaming
  • • Social media timelines
  • • Progress indicators

IndexedDB API

IndexedDB is a low-level API for client-side storage of significant amounts of structured data. It's a NoSQL database that supports transactions, indexing, and large storage capacity.

Core Concepts

  • Database: Top-level container
  • Object Store: Like tables in SQL
  • Index: For efficient queries
  • Transaction: Ensures data integrity

Advantages

  • • Large storage capacity (GB)
  • • Supports complex data types
  • • Asynchronous operations
  • • ACID transaction support

Use Cases

  • • Offline-first applications
  • • Caching large datasets
  • • User-generated content storage
  • • Complex data relationships

Implementation Patterns & Best Practices

Feature Detection Pattern

// Always check API availability if ('geolocation' in navigator) { // Use Geolocation API navigator.geolocation.getCurrentPosition(success, error); } else { // Provide fallback showFallbackMessage(); }
  • • Check feature availability before use
  • • Provide meaningful fallbacks
  • • Test across different browsers
  • • Use progressive enhancement

Error Handling

// Robust error handling try { const result = await apiCall(); handleSuccess(result); } catch (error) { handleError(error); provideFallback(); }
  • • Handle all possible error states
  • • Provide user-friendly error messages
  • • Implement retry mechanisms
  • • Log errors for debugging

Performance Optimization

  • Lazy Loading: Load APIs only when needed
  • Caching: Cache API responses when appropriate
  • Debouncing: Limit frequent API calls
  • Web Workers: Use for heavy computations
  • Monitoring: Track API usage and performance

Security Considerations

  • Permissions: Request only necessary permissions
  • Data Validation: Validate all API inputs/outputs
  • HTTPS: Use secure connections for sensitive APIs
  • Privacy: Respect user privacy preferences
  • Content Security: Implement CSP for API usage

Browser Compatibility Matrix

APIChromeFirefoxSafariEdge
Geolocation✓ v5+✓ v3.5+✓ v5+✓ v9+
Web Storage✓ v4+✓ v3.5+✓ v4+✓ v8+
Web Workers✓ v4+✓ v3.5+✓ v4+✓ v10+
WebSockets✓ v16+✓ v11+✓ v6+✓ v12+
IndexedDB✓ v24+✓ v16+✓ v10+✓ v16+

Interactive API Demonstrations

Explore live demonstrations of major HTML5 APIs including feature detection, geolocation, storage, web workers, notifications, file handling, and more.

Code Editor

<button id="copy">Copy text to clipboard</button>
<button id="share">Share this page</button>
<button id="vibrate">Vibrate (phones)</button>
<p id="out"></p>

Preview

Security & Privacy Considerations

Permission-Based APIs

  • Geolocation requires user permission
  • Notifications need explicit consent
  • Camera/microphone access is restricted
  • Always handle permission denial gracefully
  • Explain why permissions are needed

Data Security

  • Web Storage is origin-specific
  • HTTPS required for many APIs
  • Validate and sanitize file uploads
  • Be cautious with cross-origin requests
  • Implement proper error handling

Privacy Best Practices

  • Request minimal permissions
  • Clear data when not needed
  • Inform users about data usage
  • Respect Do Not Track
  • Provide opt-out mechanisms
  • Follow GDPR guidelines
  • Use secure storage methods
  • Implement data retention policies
  • Regular security audits

HTML5 APIs — step by step

1 / 4
1

Understand the HTML5 API landscape

HTML5 introduced many browser-native APIs including Geolocation, Web Storage, Canvas, Web Workers, WebSockets, and File API. These enable powerful app-like experiences without plugins.

1 of 4
🔍HTML5 APIs Are Progressively Available
Not every HTML5 API is available in every browser or environment. Always feature-detect before using an API: check if the property exists on navigator, window, or the relevant object before calling it. This prevents crashes in older or restricted environments.

🎯 Quick Check

Which HTML5 API would you use to run JavaScript in a background thread?

HTML5 APIs: summary

Key points

  • Most of these APIs need a secure context (HTTPS or localhost).
  • Permission-based APIs like Geolocation and Notifications must be requested after a user action.
  • Check support on MDN or caniuse, and feature-detect (if ("geolocation" in navigator)).

Frequently asked questions

›Are HTML5 APIs part of HTML or JavaScript?

They're Web APIs: browser features that you use from JavaScript and that are defined alongside the HTML standard.