HTML5 introduced numerous JavaScript APIs that enable powerful web applications with features previously available only in native applications. This guide covers the most important HTML5 APIs and how to use them.
The Canvas API provides a means for drawing graphics via JavaScript on a <canvas>
element. It can be used for animations, game graphics, data visualization, photo manipulation, and real-time video processing.
Category | Common Methods | Description |
---|---|---|
Rectangles | fillRect(), strokeRect(), clearRect() |
Draw filled, outlined, or clear rectangles |
Paths | beginPath(), closePath(), moveTo(), lineTo(), arc(), arcTo(), bezierCurveTo() |
Create and draw paths with lines and curves |
Path Operations | fill(), stroke(), clip() |
Fill, stroke, or create a clipping region from the current path |
Text | fillText(), strokeText(), measureText() |
Draw and measure text on the canvas |
Images | drawImage() |
Draw images, video frames, or other canvases |
Pixel Manipulation | createImageData(), getImageData(), putImageData() |
Manipulate individual pixels in the canvas |
Transformations | scale(), rotate(), translate(), transform() |
Apply transformations to the canvas context |
The Web Storage API provides mechanisms for websites to store key-value pairs locally in the user's browser, persisting beyond page refresh and between browser sessions:
Feature | localStorage | sessionStorage |
---|---|---|
Persistence | Until explicitly cleared by code or user | Until the browser tab/window is closed |
Scope | Shared across all tabs/windows from the same origin | Limited to the tab/window that created it |
Storage Limit | ~5MB per origin (varies by browser) | ~5MB per origin (varies by browser) |
Data Type | Strings only (objects need to be serialized) | Strings only (objects need to be serialized) |
Use Case | User preferences, non-sensitive persistent data | Temporary form data, single-session state |
JSON.stringify()
and deserialize with JSON.parse()
The Geolocation API allows websites to access the user's geographical location information, with the user's permission:
The HTML5 Drag and Drop API allows you to implement drag-and-drop features in web applications by making elements draggable and defining drop zones:
Event | Target | Description |
---|---|---|
dragstart |
Draggable element | Fires when the user starts dragging an element |
drag |
Draggable element | Fires continuously while the element is being dragged |
dragend |
Draggable element | Fires when the drag operation ends (drop or cancel) |
dragenter |
Drop target | Fires when a dragged element enters a valid drop target |
dragover |
Drop target | Fires continuously while a dragged element is over a drop target |
dragleave |
Drop target | Fires when a dragged element leaves a valid drop target |
drop |
Drop target | Fires when a dragged element is dropped on a valid target |
The dataTransfer
object is used to hold data that is being dragged during a drag and drop operation, and to specify the allowed drop effects:
Web Workers allow you to run JavaScript code in background threads, separate from the main execution thread of a web application. This enables computationally intensive tasks without blocking the UI:
Type | Description |
---|---|
Dedicated Workers | Used by a single script instance (most common) |
Shared Workers | Can be shared between multiple scripts or windows from the same origin |
Service Workers | Act as proxy servers that sit between web applications, the browser, and the network (used for offline support and push notifications) |
Workers do not have access to:
window
objectdocument
objectparent
objectWorkers do have access to:
navigator
objectlocation
object (read-only)XMLHttpRequest
and fetch
for network requestssetTimeout
/setInterval
functionspostMessage()
The Fetch API provides a modern interface for making HTTP requests, replacing the older XMLHttpRequest. It uses Promises for more manageable asynchronous code:
Option | Description | Example |
---|---|---|
method |
HTTP method to use | 'GET' , 'POST' , 'PUT' , 'DELETE' , etc. |
headers |
HTTP headers to include | { 'Content-Type': 'application/json' } |
body |
Body content for POST/PUT requests | JSON.stringify(data) , new FormData() , etc. |
mode |
CORS mode | 'cors' , 'no-cors' , 'same-origin' |
credentials |
Include cookies with request | 'omit' , 'same-origin' , 'include' |
cache |
How to handle cache | 'default' , 'no-store' , 'reload' , 'no-cache' |
redirect |
How to handle redirects | 'follow' , 'error' , 'manual' |
FormData
or Blob
with the Fetch APIresponse.body
and the Streams APIAbortController
to cancel requestsrequest.clone()
or response.clone()
to create copies that can be used multiple timesIndexedDB is a low-level API for client-side storage of significant amounts of structured data, including files and blobs. It's more powerful than localStorage, providing indexed database capabilities in the browser:
Concept | Description |
---|---|
Database | Container for object stores, similar to a SQL database |
Object Store | Similar to a table in a SQL database, holds records (JavaScript objects) |
Index | Provides a way to quickly locate records by properties other than the key |
Transaction | A group of operations that succeed or fail together (atomic) |
Cursor | Mechanism for iterating over multiple records in an object store or index |
Key Range | Defines a range of keys to select records from an object store or index |
The History API allows manipulation of the browser history and the current URL without a full page refresh, enabling single-page applications (SPAs) to manage browser navigation:
Method | Description | Use Case |
---|---|---|
pushState() |
Adds a new entry to the history stack | Normal navigation in a SPA; allows back button to return to previous states |
replaceState() |
Replaces the current history entry without adding a new one | Updating the URL to reflect a parameter change without creating a new history entry |
The WebSockets API enables two-way communication between a browser and a server, allowing real-time data transfer with lower overhead than HTTP:
Feature | WebSocket | HTTP |
---|---|---|
Connection | Persistent, full-duplex | Request-response, stateless |
Data Transfer | Bidirectional, simultaneous | Client requests, server responds |
Header Overhead | Low after initial handshake | Every request includes full headers |
Latency | Low (single TCP connection) | Higher (new connection per request or keep-alive) |
Use Case | Real-time applications, live data updates | Traditional web requests, REST APIs |
Allows web applications to interact with files on the user's device:
Enables web applications to display system notifications to the user:
A high-level API for processing and synthesizing audio in web applications:
Streamlines the checkout process by allowing websites to collect payment information with a native interface: