HTML - HTML Web APIs
HTML Web APIs are interfaces provided by the browser that allow web pages to interact with the user, the browser, and other web technologies beyond just HTML and CSS. They are typically accessed via JavaScript.
1. What Web APIs Are
-
Web APIs are JavaScript-accessible objects and functions that let you perform tasks like:
-
Manipulating the DOM
-
Storing data locally
-
Making network requests
-
Interacting with hardware or browser features
-
-
Examples:
fetch()
,localStorage
,Canvas API
,Geolocation API
.
2. Categories of Web APIs
Category | Examples | Description |
---|---|---|
DOM & HTML | document , Element , Event |
Access and manipulate HTML elements and handle events |
CSS | CSSStyleSheet , CSSRule |
Manipulate styles dynamically |
Network | fetch , XMLHttpRequest , WebSocket |
Communicate with servers asynchronously |
Storage | localStorage , sessionStorage , IndexedDB |
Save data on the client-side |
Multimedia | Canvas API , AudioContext , Video |
Draw graphics, play audio/video |
Geolocation & Sensors | navigator.geolocation , DeviceOrientationEvent |
Access location and device sensors |
Notifications & UI | Notification , alert , confirm |
Interact with the user |
Web Components | CustomElementRegistry , ShadowRoot |
Create reusable HTML components |
Other | WebRTC , ServiceWorker , Push API |
Advanced features like real-time communication, offline caching, push notifications |
3. How to Use a Web API
Most Web APIs are JavaScript objects or functions. Example using the Geolocation API:
<button id="getLocation">Get Location</button>
<p id="output"></p>
<script>
document.getElementById('getLocation').onclick = () => {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(position => {
document.getElementById('output').textContent =
`Latitude: ${position.coords.latitude}, Longitude: ${position.coords.longitude}`;
});
} else {
alert("Geolocation not supported.");
}
};
</script>
4. Key Points
-
Most Web APIs are asynchronous, using Promises or callbacks.
-
They require user permission for sensitive operations (like location, camera, or microphone).
-
Modern web development often combines multiple APIs (e.g.,
fetch
+IndexedDB
+ServiceWorker
) for rich applications.