HTML5 APIs Overview
Overview
HTML used to be just a document reader. With the release of HTML5, the browser transformed into a powerful operating system. HTML5 introduced JavaScript APIs (Application Programming Interfaces) that let web pages access your computer's hardware.
Today, a website can track your GPS location, use your webcam, work offline, and save gigabytes of data locally on your hard drive, all thanks to HTML5 APIs.
Syntax
Websites like Swiggy or Uber use this API to ask for your physical location (Latitude and Longitude). The browser will always popup a prompt asking the user for permission first.
<!-- This is written in JavaScript, but it's part of the HTML5 spec! -->
navigator.geolocation.getCurrentPosition(
(position) => {
console.log("Latitude: " + position.coords.latitude);
console.log("Longitude: " + position.coords.longitude);
},
(error) => {
console.error("User denied permission.");
}
);Before HTML5, websites had to use tiny 4kb cookies to remember you. Now, `localStorage` allows websites to save up to 5MB of data directly on your hard drive. If you close the tab and come back tomorrow, the data is still there!
// 1. Save data to the user's hard drive
localStorage.setItem("theme", "dark");
localStorage.setItem("username", "Kartik Rai");
// 2. Read data back (even after refreshing the page)
const userTheme = localStorage.getItem("theme");
console.log(userTheme); // prints "dark"
// 3. Delete the data
localStorage.removeItem("username");HTML5 added native drag-and-drop support. You can make any element draggable just by adding the `draggable="true"` attribute.
<!-- The user can click and drag this div across the screen -->
<div draggable="true" id="dragbox">
Drag me into the trash!
</div>Common Pitfalls
- localStorage is completely public to anyone using that browser. NEVER store sensitive data like passwords or JWT authentication tokens in localStorage.
- Interview tip: localStorage keeps data forever until manually deleted. sessionStorage keeps data only until the user closes that specific browser tab.
Real-World Example
A dark mode toggle that remembers the user's choice using localStorage:
function toggleTheme() {
const isDark = document.body.classList.toggle('dark-mode');
// Save their preference so we remember it next time they visit
if (isDark) {
localStorage.setItem('preferred-theme', 'dark');
} else {
localStorage.setItem('preferred-theme', 'light');
}
}
// When the page loads, check if they had a saved preference
window.onload = function() {
const savedTheme = localStorage.getItem('preferred-theme');
if (savedTheme === 'dark') {
document.body.classList.add('dark-mode');
}
};