JS Web APIs
Web APIs Intro
Web APIs are browser-provided features that JavaScript can use to interact with the device and the web platform: network requests, storage, location, validation, workers, and more.
Important: Web APIs are not part of core JavaScript (ECMAScript). They are provided by the browser environment.
Fetch API
The Fetch API is the modern way to make HTTP requests. It returns a Promise.
async function loadTodo() {
const res = await fetch("https://jsonplaceholder.typicode.com/todos/1");
if (!res.ok) {
throw new Error("HTTP error: " + res.status);
}
const data = await res.json();
console.log(data);
}
loadTodo().catch(console.error);
Send JSON with POST:
async function createItem() {
const res = await fetch("/api/items", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ title: "New item" })
});
const data = await res.json();
console.log(data);
}
Geolocation API
The Geolocation API can retrieve the user's approximate location (requires permission).
if ("geolocation" in navigator) {
navigator.geolocation.getCurrentPosition(
(pos) => {
console.log(pos.coords.latitude, pos.coords.longitude);
},
(err) => {
console.error("Geolocation error:", err.message);
},
{ enableHighAccuracy: true, timeout: 5000 }
);
} else {
console.log("Geolocation not supported");
}
Privacy tip: Always explain why you need location and provide a fallback.
Web History API
The History API lets you manipulate the browser history without reloading the page. This is used in SPAs.
history.pushState({ page: "about" }, "", "/about");
window.addEventListener("popstate", (e) => {
console.log("State:", e.state);
});
Replace current state (no new history entry):
history.replaceState({ page: "home" }, "", "/");
Web Pointer API
Pointer Events unify mouse, touch, and pen inputs. They simplify handling user interactions across devices.
const pad = document.querySelector("#pad");
pad.addEventListener("pointerdown", (e) => {
pad.setPointerCapture(e.pointerId);
console.log("down", e.pointerType, e.clientX, e.clientY);
});
pad.addEventListener("pointermove", (e) => {
// console.log("move", e.clientX, e.clientY);
});
pad.addEventListener("pointerup", (e) => {
console.log("up");
});
Web Storage API
Web Storage provides localStorage (persistent) and sessionStorage (per-tab session).
// Save
localStorage.setItem("theme", "light");
// Read
const theme = localStorage.getItem("theme");
console.log(theme);
// Remove
localStorage.removeItem("theme");
// Clear all
// localStorage.clear();
Store objects using JSON:
const user = { id: 1, name: "Ozan" };
localStorage.setItem("user", JSON.stringify(user));
const saved = JSON.parse(localStorage.getItem("user"));
console.log(saved.name);
Tip: Avoid storing sensitive data (tokens/passwords) in localStorage.
Validation API
The Constraint Validation API works with HTML forms. You can check validity and show built-in messages.
const form = document.querySelector("#signup");
const email = document.querySelector("#email");
form.addEventListener("submit", (e) => {
if (!form.checkValidity()) {
e.preventDefault();
form.reportValidity();
return;
}
if (!email.value.includes("@")) {
e.preventDefault();
email.setCustomValidity("Please enter a valid email");
email.reportValidity();
} else {
email.setCustomValidity("");
}
});
Web Worker API
Web Workers run JavaScript in a background thread. They are useful for heavy computations that would otherwise freeze the UI.
Main thread:
// main.js
const worker = new Worker("worker.js");
worker.postMessage({ n: 1000000 });
worker.onmessage = (e) => {
console.log("Result from worker:", e.data);
};
Worker file:
// worker.js
self.onmessage = (e) => {
const n = e.data.n;
let sum = 0;
for (let i = 0; i < n; i++) sum += i;
self.postMessage(sum);
};
Note: Workers cannot access the DOM directly. They communicate via messages.
Next Step
Continue with JS AJAX (XHR vs Fetch) or JS JSON for data exchange patterns.