HTML APIs Guide
HTML APIs Overview
HTML5 introduces various APIs to enhance web applications, enabling access to device features, local storage, background processing, and real-time data streaming.
HTML Geolocation
The Geolocation API allows web applications to access the user's geographical location.
navigator.geolocation.getCurrentPosition(successCallback, errorCallback, options);
function successCallback(position) {
const lat = position.coords.latitude;
const lon = position.coords.longitude;
console.log(`Latitude: ${lat}, Longitude: ${lon}`);
}
function errorCallback(error) {
console.error(`Error: ${error.message}`);
}
Example of retrieving the user's location:
Fetching location...
HTML Web Storage
Web Storage API provides two mechanisms: localStorage
and sessionStorage
. These allow web applications to store data locally on the user's browser.
// Save data
localStorage.setItem('key', 'value');
sessionStorage.setItem('key', 'value');
// Retrieve data
const localValue = localStorage.getItem('key');
const sessionValue = sessionStorage.getItem('key');
// Remove data
localStorage.removeItem('key');
sessionStorage.removeItem('key');
Example of using Web Storage:
Loading stored data...
HTML Web Workers
Web Workers provide a way to run scripts in the background, without affecting the performance of the main page. This allows for tasks to be performed asynchronously.
const worker = new Worker('worker.js');
worker.onmessage = function(event) {
console.log('Message from worker:', event.data);
};
worker.postMessage('Hello, Worker!');
Example of using Web Workers:
Waiting for worker response...
HTML Server-Sent Events (SSE)
Server-Sent Events (SSE) allow servers to push updates to the web page in real-time. This is useful for applications that require continuous updates, such as live notifications or news feeds.
const eventSource = new EventSource('events');
eventSource.onmessage = function(event) {
console.log('Message from server:', event.data);
};
eventSource.onerror = function(error) {
console.error('Error:', error);
};
Example of using SSE:
Waiting for updates...
0 Comments