⚡
Modern Web APIs
Advanced
140 XP
60 min
Lesson Content
Modern Web APIs
Modern browsers provide powerful APIs for building rich web applications. Learn to use these APIs effectively.
LocalStorage and SessionStorage
// localStorage - persists across sessions
localStorage.setItem('key', 'value');
const value = localStorage.getItem('key');
localStorage.removeItem('key');
// sessionStorage - cleared when tab closes
sessionStorage.setItem('key', 'value');Geolocation API
navigator.geolocation.getCurrentPosition((position) => {
console.log(position.coords.latitude, position.coords.longitude);
});Intersection Observer
const observer = new IntersectionObserver((entries) => {
entries.forEach(entry => {
if (entry.isIntersecting) {
// Element is visible
}
});
});
observer.observe(element);Web Workers
// main.js
const worker = new Worker('worker.js');
worker.postMessage('Hello');
worker.onmessage = (e) => console.log(e.data);Example Code
Use modern web APIs
// localStorage
localStorage.setItem('username', 'John');
const username = localStorage.getItem('username');
console.log('Username:', username);
// Working with JSON
const user = { name: 'Alice', age: 30 };
localStorage.setItem('user', JSON.stringify(user));
const savedUser = JSON.parse(localStorage.getItem('user'));
console.log('User:', savedUser);
// Note: Other APIs require browser environmentExpected Output:
Username: John
User: {name:Alice,age:30}Study Tips
- •Read the theory content thoroughly before practicing
- •Review the example code to understand key concepts
- •Proceed to the Practice tab when you're ready to code