Modern Web APIs: A Developer's Guide
Modern web APIs provide powerful capabilities for building feature-rich web applications. Let's explore some of the most useful APIs.
Web Storage APIs
Local Storage
// Store data
localStorage.setItem(
"user",
JSON.stringify({
id: 1,
name: "John Doe",
preferences: { theme: "dark" },
})
);
// Retrieve data
const user = JSON.parse(localStorage.getItem("user") || "{}");
// Remove data
localStorage.removeItem("user");
IndexedDB
const dbName = "myDatabase";
const request = indexedDB.open(dbName, 1);
request.onupgradeneeded = (event) => {
const db = event.target.result;
const store = db.createObjectStore("users", { keyPath: "id" });
store.createIndex("name", "name", { unique: false });
};
request.onsuccess = (event) => {
const db = event.target.result;
const transaction = db.transaction(["users"], "readwrite");
const store = transaction.objectStore("users");
store.add({ id: 1, name: "John Doe" });
};
Web Workers
Background Processing
// main.js
const worker = new Worker("worker.js");
worker.postMessage({ data: [1, 2, 3, 4, 5] });
worker.onmessage = (event) => {
console.log("Result:", event.data);
};
// worker.js
self.onmessage = (event) => {
const { data } = event.data;
const result = data.reduce((a, b) => a + b, 0);
self.postMessage(result);
};
WebSocket API
Real-time Communication
class WebSocketClient {
private ws: WebSocket;
constructor(url: string) {
this.ws = new WebSocket(url);
this.setupEventListeners();
}
private setupEventListeners() {
this.ws.onopen = () => {
console.log("Connected to WebSocket");
};
this.ws.onmessage = (event) => {
const data = JSON.parse(event.data);
this.handleMessage(data);
};
this.ws.onerror = (error) => {
console.error("WebSocket error:", error);
};
this.ws.onclose = () => {
console.log("Disconnected from WebSocket");
};
}
public send(data: any) {
this.ws.send(JSON.stringify(data));
}
private handleMessage(data: any) {
// Handle incoming messages
console.log("Received:", data);
}
}
WebRTC
Peer-to-Peer Communication
class WebRTCClient {
private peerConnection: RTCPeerConnection;
private dataChannel: RTCDataChannel;
constructor() {
this.peerConnection = new RTCPeerConnection({
iceServers: [{ urls: "stun:stun.l.google.com:19302" }],
});
this.setupDataChannel();
}
private setupDataChannel() {
this.dataChannel = this.peerConnection.createDataChannel("data");
this.dataChannel.onopen = () => {
console.log("Data channel opened");
};
this.dataChannel.onmessage = (event) => {
console.log("Received:", event.data);
};
}
public async createOffer() {
const offer = await this.peerConnection.createOffer();
await this.peerConnection.setLocalDescription(offer);
return offer;
}
public async handleAnswer(answer: RTCSessionDescriptionInit) {
await this.peerConnection.setRemoteDescription(answer);
}
}
Web Push API
Push Notifications
class PushNotificationService {
async requestPermission() {
const permission = await Notification.requestPermission();
if (permission === "granted") {
const registration = await navigator.serviceWorker.ready;
const subscription = await registration.pushManager.subscribe({
userVisibleOnly: true,
applicationServerKey: "YOUR_PUBLIC_VAPID_KEY",
});
return subscription;
}
}
async sendNotification(subscription: PushSubscription) {
const response = await fetch("/api/send-push", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(subscription),
});
return response.json();
}
}
Best Practices
- Handle errors gracefully
- Implement proper security measures
- Consider browser compatibility
- Use appropriate fallbacks
- Implement proper cleanup
- Follow API guidelines
- Test thoroughly
- Monitor performance
Conclusion
Modern web APIs provide:
- Enhanced user experiences
- Real-time capabilities
- Offline functionality
- Better performance
- Rich features