Module 2: Browser APIs
Beyond the DOM and events, browsers expose many built-in APIs — JavaScript objects that give access to real device and browser features.
The Fetch API
The standard way to make network requests (get or send data) from the browser — covered in more depth alongside Promises in the next chapters:
async function getUsers() {
let response = await fetch("https://api.example.com/users");
let data = await response.json();
console.log(data);
}
getUsers();
URL, History & Location APIs
// URL — parse and build URLs safely
let url = new URL("https://example.com/search?q=js&page=2");
url.searchParams.get("q"); // "js"
url.searchParams.set("page", "3");
url.toString();
// Location — info about the current page's URL
console.log(location.href); // full URL
console.log(location.pathname); // "/search"
location.href = "/dashboard"; // navigates the page
// History — control the back/forward stack, for SPA-style navigation
history.pushState({}, "", "/new-page"); // changes URL without a full reload
history.back();
history.forward();
Clipboard, Geolocation & Notifications
// Clipboard — copy text programmatically
navigator.clipboard.writeText("Copied text!");
// Geolocation — ask the user's location (requires their permission)
navigator.geolocation.getCurrentPosition((position) => {
console.log(position.coords.latitude, position.coords.longitude);
});
// Notifications — show a system-level notification (requires permission)
Notification.requestPermission().then((permission) => {
if (permission === "granted") {
new Notification("Hello!", { body: "This is a browser notification" });
}
});
File API & Drag and Drop
// File API — read a file the user selected via an <input type="file">
let input = document.querySelector("input[type=file]");
input.addEventListener("change", (event) => {
let file = event.target.files[0];
console.log(file.name, file.size, file.type);
let reader = new FileReader();
reader.onload = () => console.log(reader.result); // file contents
reader.readAsText(file);
});
// Drag and Drop — allow dropping files/elements onto the page
dropZone.addEventListener("dragover", (e) => e.preventDefault());
dropZone.addEventListener("drop", (e) => {
e.preventDefault();
let files = e.dataTransfer.files;
console.log("Dropped:", files[0].name);
});
Canvas Overview
<canvas> gives JavaScript a pixel surface to draw on directly — shapes, images,
text, and animations, all via code, used for charts, games, and image editing.
let canvas = document.querySelector("canvas");
let ctx = canvas.getContext("2d");
ctx.fillStyle = "#C41230";
ctx.fillRect(10, 10, 150, 100); // x, y, width, height
ctx.beginPath();
ctx.arc(100, 200, 50, 0, Math.PI * 2); // circle
ctx.fillStyle = "#F5A623";
ctx.fill();
ctx.font = "20px sans-serif";
ctx.fillText("Hello Canvas", 10, 150);