HTML5 APIs
We have went through all the elements that help us build websites. Next is HTML APIs,it is important to know about the HTML5 APIs while creating websites, as these APIs significantly enhance the capabilities of web applications, allowing for more interactive, responsive, and feature rich experiences directly in the browser.
Canvas API
Section titled “Canvas API”The Canvas API is a powerful tool for drawing graphics and creating animations directly in the browser using JavaScript. It provides a means to draw 2D shapes, images, and text on a canvas element.
Canvas helps us render graphics on a pixel-by-pixel basis giving more fine grained control to draw shapes and images, it supports 2D and 3D WebGL contexts. It is super useful for data visualization, game graphics, and complex animations.
const canvas = document.getElementById("myCanvas");const ctx = canvas.getContext("2d");ctx.fillStyle = "red";ctx.fillRect(10, 10, 150, 100);
Geolocation API
Section titled “Geolocation API”You might have seen a pop up asking for your location access while visiting some sites, well Geolocation API is behind this. This API allows web applications to access the user’s geographical location if the user grants permission. Once the access is granted, API will provide us the developer latitude, longitude coordinates, altitude, heading, and speed information of the user, you can use it for mapping purposes using Google map, Mapbox etc, location-based services, and personalized content delivery. Data can be from GPS, Wi-Fi, IP geolocation permitting us to access users’ data either in a one-time location request, or can be used for continuous watching.
if ("geolocation" in navigator) { navigator.geolocation.getCurrentPosition(function (position) { console.log("Latitude:", position.coords.latitude); console.log("Longitude:", position.coords.longitude); });}
Local Storage and Session Storage
Section titled “Local Storage and Session Storage”These APIs provide mechanisms to store key-value pairs in a web browser, allowing web applications to save data locally on a user’s device.
Local Storage
Section titled “Local Storage”This API helps us to persist data even after the browser window is closed. It comes with about 5-10 MB of data storage, data will be available until explicitly deleted by code (no automatic built-in expiration mechanism), cleared by the user, or browser storage is cleared. Usually used for saving user preferences and settings, for example, shopping cart items in e-commerce applications helping application state to be remembered across sessions.
Keep in mind this is a Synchronous API meaning code execution stops until the localstorage api calls are completed while coming across the code for the same which can impact performance if overused.
// Storing datalocalStorage.setItem("username", "JohnDoe");localStorage.setItem("theme", "dark");
// Retrieving dataconst username = localStorage.getItem("username"); // Returns 'JohnDoe'
// Removing specific itemlocalStorage.removeItem("username");
// Clearing all local storage for the domainlocalStorage.clear();
Session Storage
Section titled “Session Storage”Data is cleared when the page session ends, it provides developers to temporarily store 5-10 MB data. data is cleared when the tab or window is closed.
It can be used for storing form data during navigation within a single session and one time use data like single session authentication tokens. let’s say if we have a shopping cart where the data needs to be reset after closing the browser, we can use session storage in place of localstorage. Just like local storage, session storage is also Synchronous API, hence be mindful of overuse.
// Storing datasessionStorage.setItem( "formData", JSON.stringify({ name: "John", email: "john@example.com" }),);sessionStorage.setItem("pageVisits", "5");
// Retrieving dataconst formData = JSON.parse(sessionStorage.getItem("formData"));
// Removing specific itemsessionStorage.removeItem("pageVisits");
// Clearing all session storage for this tab/windowsessionStorage.clear();
Both session and local storage APIs store data in plain text, with no encryption, hence its not suitable for sensitive information storage like credit card details and passwords.
Web Workers
Section titled “Web Workers”Web Workers allow you to run scripts in background threads, separate from the main execution thread of a web application. This is particularly useful for running computationally CPU-intensive tasks without affecting the responsiveness of the user interface.
Communication between with the main thread via a messaging system, rendering API not able to directly access the DOM or window object
// Main scriptconst worker = new Worker("worker.js");worker.postMessage("Start processing");worker.onmessage = function (e) { console.log("Received from worker:", e.data);};
// worker.jsself.onmessage = function (e) { console.log("Received from main script:", e.data); // Do some intensive processing here self.postMessage("Processing complete");};