HTML5 APIs & Browser Features
HTML5 APIs & Browser Features
HTML5 APIs are browser-provided interfaces that allow web applications to access advanced capabilities such as local storage, device location, graphics, background processing, network communication and browser history.
HTML provides the structure of a webpage, while browser APIs allow JavaScript to interact with browser features and device capabilities.
Most HTML5 APIs are accessed through JavaScript. HTML provides elements and attributes, while JavaScript uses browser APIs to create interactive and application-like experiences.
1. What is an API?
API stands for Application Programming Interface.
An API provides a defined way for one software component to communicate with another.
In web development, browser APIs allow JavaScript programs to communicate with browser functionality.
Simple Example
navigator.geolocation.getCurrentPosition(
function(position) {
console.log(position.coords.latitude);
console.log(position.coords.longitude);
}
);
Here, JavaScript uses the browser's Geolocation API.
2. Important HTML5 and Browser APIs
| API / Feature | Purpose |
|---|---|
| Web Storage | Stores data in the browser. |
| Geolocation | Provides the user's geographic location with permission. |
| Canvas | Creates graphics using JavaScript. |
| Drag and Drop | Allows elements to be dragged and dropped. |
| Web Workers | Runs JavaScript in background threads. |
| Fetch API | Makes network requests from JavaScript. |
| WebSocket API | Provides persistent two-way communication. |
| History API | Manipulates browser session history. |
| Notifications API | Displays browser notifications with permission. |
| Fullscreen API | Allows content to enter fullscreen mode. |
3. Web Storage API
The Web Storage API allows web applications to store key-value data in the browser.
The two main storage mechanisms are:
- localStorage
- sessionStorage
4. localStorage
localStorage stores data that remains available across browser sessions until it is removed.
Store Data
localStorage.setItem(
"username",
"Alex"
);
Read Data
const username =
localStorage.getItem("username");
console.log(username);
Remove One Item
localStorage.removeItem("username");
Clear Storage
localStorage.clear();
5. sessionStorage
sessionStorage stores data for the current browser tab/session.
sessionStorage.setItem(
"theme",
"dark"
);
const theme =
sessionStorage.getItem("theme");
console.log(theme);
| Feature | localStorage | sessionStorage |
|---|---|---|
| Persistence | Persists across browser sessions. | Associated with the current session/tab. |
| API | localStorage | sessionStorage |
| Typical Use | Preferences and non-sensitive client-side data. | Temporary session-specific data. |
Do not store passwords, authentication secrets or other highly sensitive information in Web Storage.
6. Geolocation API
The Geolocation API allows a webpage to request the user's geographic location.
The browser requires user permission before providing location information.
Example
navigator.geolocation.getCurrentPosition(
function(position) {
console.log(
"Latitude:",
position.coords.latitude
);
console.log(
"Longitude:",
position.coords.longitude
);
},
function(error) {
console.log(
"Unable to get location."
);
}
);
Location is sensitive information. Websites should request it only when necessary and clearly explain why it is needed.
7. Canvas API
The <canvas> element provides a drawable area that JavaScript can use to create graphics.
<canvas
id="drawingArea"
width="400"
height="200">
Your browser does not support canvas.
</canvas>
Drawing with JavaScript
const canvas =
document.getElementById("drawingArea");
const ctx =
canvas.getContext("2d");
ctx.fillRect(
50,
40,
150,
80
);
Canvas can be used for games, diagrams, visualizations, drawing applications and other graphics-based interfaces.
Canvas is essentially a drawing surface. The graphics themselves are rendered through JavaScript.
8. Canvas vs SVG
| Feature | Canvas | SVG |
|---|---|---|
| Type | Pixel-based drawing surface. | Vector-based graphics. |
| Manipulation | Usually through JavaScript drawing operations. | Elements can be manipulated individually. |
| Suitable For | Games and dynamic graphics. | Scalable diagrams, icons and illustrations. |
9. HTML Drag and Drop API
HTML provides attributes and events that can be used to implement drag-and-drop interactions.
Draggable Element
<div
id="item"
draggable="true">
Drag Me
</div>
JavaScript
const item =
document.getElementById("item");
item.addEventListener(
"dragstart",
function(event) {
event.dataTransfer.setData(
"text/plain",
"item"
);
}
);
Common drag-and-drop events include dragstart, dragover and drop.
10. Web Workers
A Web Worker allows JavaScript code to run in a background thread, helping keep the main page responsive during computationally intensive tasks.
main.js
const worker =
new Worker("worker.js");
worker.postMessage(100);
worker.onmessage =
function(event) {
console.log(
"Result:",
event.data
);
};
worker.js
self.onmessage =
function(event) {
const result =
event.data * event.data;
self.postMessage(result);
};
Web Workers do not directly manipulate the DOM in the same way as the main page script. Communication normally occurs through messages.
11. Fetch API
The Fetch API provides a modern interface for making HTTP requests.
GET Request
fetch("/api/courses")
.then(function(response) {
return response.json();
})
.then(function(data) {
console.log(data);
})
.catch(function(error) {
console.error(error);
});
Using async/await
async function loadCourses() {
try {
const response =
await fetch("/api/courses");
const data =
await response.json();
console.log(data);
} catch (error) {
console.error(error);
}
}
Fetch returns a Promise. It is commonly used to retrieve or send data without requiring a full page reload.
12. Fetch API — POST Request
fetch("/api/courses", {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({
title: "HTML",
level: "Beginner"
})
})
.then(function(response) {
return response.json();
})
.then(function(data) {
console.log(data);
});
The method specifies the HTTP method, headers provide metadata and body contains the request data.
13. WebSocket API
The WebSocket API provides persistent, two-way communication between a client and server.
const socket =
new WebSocket(
"wss://example.com/socket"
);
socket.onopen =
function() {
socket.send(
"Hello Server"
);
};
socket.onmessage =
function(event) {
console.log(
"Server:",
event.data
);
};
WebSockets are useful for applications requiring real-time communication.
| Application | Why WebSockets? |
|---|---|
| Chat applications | Real-time messages. |
| Live dashboards | Continuous updates. |
| Multiplayer games | Low-latency communication. |
| Collaborative tools | Real-time synchronization. |
14. History API
The History API allows JavaScript to manipulate the browser's session history without necessarily performing a complete page navigation.
pushState()
history.pushState(
{},
"",
"/courses/html"
);
replaceState()
history.replaceState(
{},
"",
"/courses/css"
);
Back
history.back();
The History API is important in applications that manage navigation dynamically, including many single-page applications.
15. Notifications API
The Notifications API can display notifications outside the webpage interface, subject to browser support and user permission.
Notification.requestPermission()
.then(function(permission) {
if (permission === "granted") {
new Notification(
"Course Update",
{
body:
"A new HTML lesson is available."
}
);
}
});
Websites should not repeatedly request notification permission without a meaningful reason.
16. Fullscreen API
The Fullscreen API allows an element to request fullscreen presentation.
const video =
document.getElementById("video");
video.requestFullscreen();
Fullscreen behavior is subject to browser security and user interaction requirements.
17. Clipboard API
The Clipboard API provides programmatic access to clipboard operations in supported contexts.
async function copyText() {
await navigator.clipboard.writeText(
"HTML is the standard markup language."
);
}
Clipboard operations can be restricted by browser security policies and permissions.
18. Media Capture
The MediaDevices API can request access to devices such as cameras and microphones, subject to permissions.
navigator.mediaDevices
.getUserMedia({
video: true,
audio: true
})
.then(function(stream) {
console.log(
"Media stream available."
);
})
.catch(function(error) {
console.error(error);
});
Camera and microphone access requires user permission and should be handled responsibly.
19. Online and Offline Detection
Browsers expose information about the network connectivity state through navigator.onLine and related events.
if (navigator.onLine) {
console.log("Online");
} else {
console.log("Offline");
}
Applications can also listen for connectivity-related events.
window.addEventListener(
"online",
function() {
console.log("Connection restored.");
}
);
window.addEventListener(
"offline",
function() {
console.log("Connection lost.");
}
);
navigator.onLine should not be treated as a definitive guarantee that a server or particular internet service is reachable.
20. Custom Data Attributes
HTML allows developers to store custom data using data-* attributes.
<button
id="courseButton"
data-course-id="101"
data-level="beginner">
HTML Course
</button>
Access Using JavaScript
const button =
document.getElementById("courseButton");
console.log(
button.dataset.courseId
);
console.log(
button.dataset.level
);
Custom data attributes are useful for storing small pieces of application-specific information associated with an element.
21. requestAnimationFrame()
requestAnimationFrame() allows JavaScript to schedule animation updates in a way designed for browser rendering.
function animate() {
// Update animation state here.
requestAnimationFrame(animate);
}
requestAnimationFrame(animate);
It is commonly used for smooth browser-based animations.
22. Feature Detection
Browser capabilities can vary. A web application can test whether a particular API exists before using it.
if ("geolocation" in navigator) {
console.log(
"Geolocation is available."
);
} else {
console.log(
"Geolocation is not available."
);
}
Prefer feature detection over assuming that every browser supports every API.
23. Browser API Security and Permissions
Browser APIs that access sensitive capabilities are subject to security restrictions.
| Capability | Typical Security Consideration |
|---|---|
| Geolocation | User permission is required. |
| Camera | User permission is required. |
| Microphone | User permission is required. |
| Notifications | User permission is required. |
| Clipboard | Browser security policies apply. |
| Fullscreen | User interaction and browser security restrictions may apply. |
Browser APIs are designed with security and user privacy restrictions so that webpages cannot freely access sensitive device capabilities.
24. Practical Project — Browser Feature Dashboard
Create a small webpage that demonstrates several browser APIs.
Required Features
- Save a username using localStorage.
- Display the saved username when the page loads.
- Display the user's location after permission is granted.
- Provide a canvas drawing area.
- Fetch sample data from a web API.
- Display online/offline status.
- Provide a notification button.
Advanced Challenge
Add a Web Worker that performs a computationally intensive calculation without blocking the main interface.
25. Interview Questions
1. What is an HTML5 API?
View Answer
An HTML5 or browser API provides a standardized interface that allows web applications to interact with browser features and device capabilities.
2. What is the difference between localStorage and sessionStorage?
View Answer
localStorage persists data across browser sessions, whereas sessionStorage is associated with the current browser session/tab.
3. What is the purpose of Web Workers?
View Answer
Web Workers allow JavaScript code to execute in a background thread so that computationally intensive work does not unnecessarily block the main interface.
4. What is the Fetch API?
View Answer
The Fetch API provides a modern JavaScript interface for making network requests and handling HTTP responses using Promises.
5. What is the difference between Fetch and WebSocket?
View Answer
Fetch is commonly used for request-response communication, while WebSocket provides a persistent two-way communication channel suitable for real-time applications.
6. Why does the Geolocation API require permission?
View Answer
Geographic location is sensitive user information, so browsers require user authorization before providing it to a website.
7. What is the purpose of the Canvas API?
View Answer
Canvas provides a drawing surface that JavaScript can use to render graphics, animations, visualizations and games.
26. Exam Questions
Q1. Name the two Web Storage mechanisms.
Answer
localStorage and sessionStorage.
Q2. Which API is used to access the user's geographic location?
Answer
The Geolocation API.
Q3. What is the purpose of the Canvas element?
Answer
It provides a drawing surface that can be controlled using JavaScript to create graphics and visual content.
Q4. Which API is suitable for real-time, two-way client-server communication?
Answer
The WebSocket API.
Q5. What is the main advantage of Web Workers?
Answer
They allow JavaScript tasks to execute in background threads, helping prevent computationally intensive operations from blocking the main page.
Q6. Write JavaScript to store and retrieve a value using localStorage.
Answer
localStorage.setItem(
"course",
"HTML"
);
const course =
localStorage.getItem("course");
console.log(course);
Q7. What is feature detection?
Answer
Feature detection means checking whether a browser supports a particular API or capability before using it.
27. Common Mistakes
| Mistake | Better Practice |
|---|---|
| Storing passwords in localStorage | Never use Web Storage for highly sensitive secrets. |
| Requesting location immediately | Explain why location is required and request it appropriately. |
| Assuming every browser supports an API | Use feature detection. |
| Blocking the UI with heavy calculations | Consider Web Workers for suitable background tasks. |
| Using WebSockets for every request | Choose the communication method according to the application's requirements. |
| Ignoring API errors | Handle rejected Promises and API failures. |
| Requesting excessive permissions | Request only the capabilities genuinely needed. |
28. Quick Revision
| Feature | Key Point |
|---|---|
| API | Interface for communication between software components. |
| localStorage | Persistent browser key-value storage. |
| sessionStorage | Storage associated with the current session/tab. |
| Geolocation | Accesses geographic location with permission. |
| Canvas | JavaScript-based graphics drawing surface. |
| Drag and Drop | Supports drag-and-drop interactions. |
| Web Worker | Runs JavaScript in a background thread. |
| Fetch | Makes HTTP/network requests using a Promise-based API. |
| WebSocket | Persistent two-way communication. |
| History API | Manages browser session history. |
| Notifications | Displays browser notifications with permission. |
| Fullscreen | Allows content to enter fullscreen mode. |
| Clipboard | Provides programmatic clipboard operations subject to security restrictions. |
| MediaDevices | Provides access to supported cameras and microphones with permission. |
| Feature Detection | Checks whether a browser supports a capability before using it. |
Storage → Data | Geolocation → Location | Canvas → Graphics | Worker → Background Processing | Fetch → HTTP Requests | WebSocket → Real-Time Communication | History → Browser Navigation