JavaScript · Lesson 32 / 32 · English
Web APIs
Understand the idea. Change the code. Build confidence with one focused experiment.
Read this lesson in தமிழ் ↗.
Start with the idea
Web APIs are capabilities supplied by the browser, not the core JavaScript language. This example uses URLSearchParams to read a course filter and a timer to update the page.
Learning goal: Explain what the example does, predict its result, and change it to solve the practice task.
Step-by-step lesson notes
Browser Web APIs
Browsers expose many built-in APIs beyond the DOM. These let you work with storage, geolocation, notifications, and much more.
Web Storage
// localStorage — persists until cleared
localStorage.setItem("user", JSON.stringify({ name: "Alice" }));
const user = JSON.parse(localStorage.getItem("user"));
localStorage.removeItem("user");
localStorage.clear(); // clear all
// sessionStorage — persists until tab closes
sessionStorage.setItem("token", "abc123");
const token = sessionStorage.getItem("token");
// Check storage capacity
function getStorageUsed() {
let total = 0;
for (const key in localStorage) {
total += localStorage[key].length * 2; // bytes
}
return (total / 1024).toFixed(2) + " KB";
}Timers
// setTimeout — run once after delay
const timeoutId = setTimeout(() => {
console.log("Runs after 2 seconds");
}, 2000);
clearTimeout(timeoutId); // cancel it
// setInterval — run repeatedly
const intervalId = setInterval(() => {
console.log("Runs every second");
}, 1000);
clearInterval(intervalId); // stop it
// requestAnimationFrame — for smooth animations
function animate() {
// update animation frame
requestAnimationFrame(animate);
}
requestAnimationFrame(animate);Other Useful APIs
// Geolocation
navigator.geolocation.getCurrentPosition(
pos => console.log(pos.coords.latitude, pos.coords.longitude),
err => console.error(err.message)
);
// Clipboard
await navigator.clipboard.writeText("Copied text!");
const text = await navigator.clipboard.readText();
// Notifications
const permission = await Notification.requestPermission();
if (permission === "granted") {
new Notification("Hello!", {
body: "Notification message",
icon: "/icon.png"
});
}
// History API
history.pushState({ page: 1 }, "Page 1", "/page1");
history.back();
history.go(-2);
// URL API
const url = new URL("https://example.com/path?q=hello&page=2");
console.log(url.hostname); // "example.com"
console.log(url.pathname); // "/path"
console.log(url.searchParams.get("q")); // "hello"
url.searchParams.set("page", "3");
console.log(url.toString());Web Workers let you run JavaScript in a background thread, keeping the main thread free for UI rendering. Use them for CPU-intensive tasks like data processing.
A complete example
This is a complete HTML document. Use the HTML preview editor below, not the Node console. Press Run to refresh the rendered page.
<!doctype html>
<html lang="en"><meta charset="utf-8"><title>Web API practice</title>
<body><p id="course"></p><p id="status">Preparing</p>
<script>
const params = new URLSearchParams("course=javascript&level=beginner");
document.querySelector("#course").textContent = params.get("course");
setTimeout(() => {
document.querySelector("#status").textContent = "Ready";
}, 300);
</script></body></html>Predict first. Reveal the expected result.
Course text: javascript Status changes from Preparing to Ready after the timer callback runs.
Make one change. See what happens.
For this browser example, interact with the rendered preview after pressing Run.
Wait for the editor to load, then load this example and press Run.
Powered by the free OneCompiler editor. Code you run is sent to that external service. Keep personal data and secret keys out of your examples.
Put the idea to work
Practice challenge
Read the level parameter and display it beside the course.
Reveal the answer and reasoning
Use params.get("level"); it returns "beginner". A missing parameter returns null.
One mistake to avoid: A timer delay is a minimum wait, not an exact execution time. Browser APIs differ in permissions and availability; handle missing capabilities.
Your learning checkpoint
- Explain the example in your own words.
- Complete the challenge before revealing its answer.
- Describe the common mistake and how to avoid it.