Browser APIs
Browser APIs (Application Programming Interfaces) are powerful tools provided by web browsers that allow developers to interact with and manipulate browser features, such as the DOM, user interactions, and external services like geolocation, storage, or networking. These APIs make your web applications interactive and dynamic.
What are Browser APIs?
Browser APIs are built-in features provided by modern web browsers. You can use them directly in JavaScript without needing to install anything. They enable functionality like:
- Manipulating web pages
- Handling user events
- Communicating with servers
- Working with multimedia (audio, video, etc.)
- Using hardware features like a camera or GPS
Common Browser APIs
Here's a quick overview of some widely used browser APIs:
DOM API
The DOM API is used to interact with the structure and content of the webpage.
let title = document.querySelector("h1"); title.textContent = "Updated Title";
Console API
Used for debugging purposes by logging messages.
console.log("Hello, World!"); // Logs a message console.error("This is an error!"); // Logs an error message
Alert, Confirm, and Prompt
Used to display dialogs to the user.
alert("This is an alert!"); // Displays a simple message let confirmed = confirm("Are you sure?"); // OK = true, Cancel = false console.log(confirmed); let name = prompt("What's your name?"); console.log("Hello, " + name);
Geolocation API
Used to get the user’s location (with their permission).
if (navigator.geolocation) { navigator.geolocation.getCurrentPosition((position) => { console.log("Latitude:", position.coords.latitude); console.log("Longitude:", position.coords.longitude); }); } else { console.log("Geolocation is not supported by your browser."); }
Fetch API
Used to fetch data from a server or API.
fetch("https://jsonplaceholder.typicode.com/posts/1") .then((response) => response.json()) .then((data) => { console.log(data); }) .catch((error) => { console.error("Error:", error); });
Local Storage and Session Storage
Store data in the browser.
Local Storage
Data persists even after the browser is closed.
localStorage.setItem("username", "Alice"); console.log(localStorage.getItem("username")); // Alice
Session Storage
Data is cleared when the browser tab is closed.
sessionStorage.setItem("sessionKey", "12345"); console.log(sessionStorage.getItem("sessionKey")); // 12345
Web APIs for Timers
Used to run code after a delay or repeatedly.
setTimeout
Runs code after a delay.
setTimeout(() => { console.log("This runs after 2 seconds!"); }, 2000);
setInterval
Runs code repeatedly at intervals.
let counter = 0; let interval = setInterval(() => { counter++; console.log("Counter:", counter); if (counter === 5) { clearInterval(interval); // Stops the interval } }, 1000);
Clipboard API
Allows copying and pasting text.
navigator.clipboard.writeText("Hello, Clipboard!").then(() => { console.log("Text copied to clipboard!"); });
Notification API
Used to show browser notifications.
if (Notification.permission === "granted") { new Notification("Hello! This is a notification."); } else if (Notification.permission !== "denied") { Notification.requestPermission().then((permission) => { if (permission === "granted") { new Notification("Thanks for allowing notifications!"); } }); }
Canvas API
Allows drawing graphics on a webpage.
let canvas = document.getElementById("myCanvas"); let context = canvas.getContext("2d"); context.fillStyle = "blue"; context.fillRect(20, 20, 100, 50); // Draws a blue rectangle
Audio and Video API
Controls media playback.
let video = document.querySelector("video"); video.play(); // Plays the video video.pause(); // Pauses the video
Drag and Drop API
Adds drag-and-drop functionality to elements.
<div id="dragMe" draggable="true">Drag me!</div> <script> let draggable = document.getElementById("dragMe"); draggable.addEventListener("dragstart", () => { console.log("Dragging started!"); }); </script>
Combining APIs: A Practical Example
Creating a Simple To-Do App
<div> <input type="text" id="todoInput" placeholder="Enter a task" /> <button onclick="addTodo()">Add Task</button> <ul id="todoList"></ul> </div>
function addTodo() { let input = document.getElementById("todoInput"); let task = input.value; if (task) { let list = document.getElementById("todoList"); let newTask = document.createElement("li"); newTask.textContent = task; // Add a remove button let removeButton = document.createElement("button"); removeButton.textContent = "Remove"; removeButton.onclick = () => list.removeChild(newTask); newTask.appendChild(removeButton); list.appendChild(newTask); input.value = ""; // Clear input } }