Web APIs Documentation
Explore the powerful set of Web APIs available for building modern, interactive, and feature-rich web applications.
Fetch API
The Fetch API provides a modern interface for making asynchronous network requests. It's a more powerful and flexible replacement for the older XMLHttpRequest object.
Key Features:
async function fetchData(url) {
try {
const response = await fetch(url);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data = await response.json();
console.log(data);
} catch (error) {
console.error('Error fetching data:', error);
}
}
fetchData('https://api.example.com/data');
Web Storage API
Web Storage provides mechanisms for the client-side storage of data. It consists of two main objects: localStorage and sessionStorage.
Key Features:
localStorage: Stores data with no expiration date.sessionStorage: Stores data for one session (until the browser tab is closed).- Methods:
setItem(),getItem(),removeItem(),clear().
// Local Storage
localStorage.setItem('username', 'JohnDoe');
const username = localStorage.getItem('username');
console.log(username); // JohnDoe
localStorage.removeItem('username');
// Session Storage
sessionStorage.setItem('theme', 'dark');
const theme = sessionStorage.getItem('theme');
console.log(theme); // dark
WebSockets API
WebSockets provide a full-duplex communication channel over a single TCP connection. This allows for real-time, bidirectional data transfer between the client and server.
Key Features:
- Establishing a Connection
- Event Handling:
onopen,onmessage,onerror,onclose. - Sending Data:
send()method.
const socket = new WebSocket('wss://echo.websocket.org');
socket.onopen = () => {
console.log('WebSocket connection established');
socket.send('Hello Server!');
};
socket.onmessage = (event) => {
console.log('Message from server:', event.data);
};
socket.onerror = (error) => {
console.error('WebSocket error:', error);
};
socket.onclose = () => {
console.log('WebSocket connection closed');
};
Geolocation API
The Geolocation API allows you to access the geographical location of the user's device. This requires user permission.
Key Features:
getCurrentPosition(): Gets the current location once.watchPosition(): Watches for changes in position.- Error Handling
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(
(position) => {
const latitude = position.coords.latitude;
const longitude = position.coords.longitude;
console.log(`Latitude: ${latitude}, Longitude: ${longitude}`);
},
(error) => {
console.error('Geolocation error:', error.message);
}
);
} else {
console.log('Geolocation is not supported by this browser.');
}
Canvas API
The HTML Canvas element provides a means for drawing graphics via JavaScript. It's often used for animations, games, data visualizations, and image manipulation.
Key Features:
- Getting Started with Canvas
- Drawing Shapes: Rectangles, arcs, lines.
- Text Rendering
- Image Manipulation
- Animation Techniques
Below is a simple example of drawing a rectangle:
<canvas id="myCanvas" width="200" height="100" style="border:1px solid #000;"></canvas>
<script>
const canvas = document.getElementById('myCanvas');
const ctx = canvas.getContext('2d');
ctx.fillStyle = '#FF0000'; // Red
ctx.fillRect(10, 10, 150, 80); // x, y, width, height
</script>
Web Components
Web Components are a set of web platform APIs that allow you to create new custom, reusable, encapsulated HTML tags to use in web pages and web applications.
Key Features:
- Custom Elements: Define new HTML elements.
- Shadow DOM: Encapsulate styles and markup.
- HTML Templates: Use
<template>and<slot>for reusable markup.
Web Components offer a powerful way to build modular and maintainable front-end architectures.