Welcome back to the third part of our series on essential Web APIs! If you haven’t had the opportunity to explore Part 2 yet, where we extensively covered the nuances of the Web History API and Web Storage API, I encourage you to catch up here to gain valuable insights into efficiently managing browser history and local data storage. And for newcomers, don’t overlook Part 1, where we thoroughly examined the fundamental principles of the Web Forms API, which you can access right here. In this segment, we’ll be venturing into additional Web APIs, including Web Workers, Web Fetch, and Web Geolocation, which elevate web development possibilities.
Let’s start our journey into understanding these fundamental tools for web development.
Web Workers API:
Web Workers provide the capability to execute JavaScript code independently in the background, distinct from the primary execution thread. This enables tasks to be performed without blocking the user interface. Let’s see an example:
Here’s a simple example demonstrating the usage of Web Workers API:
HTML:
<button onclick="startWorker()">Start Worker</button>
JavaScript:
let worker; function startWorker() { if (typeof Worker !== "undefined") { if (typeof worker == "undefined") { worker = new Worker("worker.js"); } worker.onmessage = function (event) { console.log("Message received from worker: " + event.data); }; } else { console.log("Web Workers not supported in this browser."); } }
Explanation:
In HTML, a button is created to start the web worker. In JavaScript, the ‘startWorker()’ function checks if the browser supports web workers. If the capability is available, it establishes a fresh web worker and designates an ‘onmessage’ event handler to accept messages from the worker.
worker.js:
setInterval(() => { postMessage("Hello from the worker!"); }, 1000);
Explanation:
In the worker.js file, we define the background task the worker will perform. In this instance, the worker transmits a message “Hello from the worker!”. Subsequently, data is dispatched to the main script at one-second intervals via the postMessage() method. We use setInterval() to repeat this process every second.
Output:
Web Fetch API:
The Fetch API furnishes a means to asynchronously retrieve resources, such as JSON or HTML, from the network. Its capabilities surpass those of XMLHttpRequest, offering a more robust and adaptable approach to making HTTP requests. Below is a summary of its operational capabilities:
HTML:
<button onclick="fetchData()">Fetch Data</button>
JavaScript:
function fetchData() { fetch("https://jsonplaceholder.typicode.com/posts/1") .then((response) => response.json()) .then((data) => console.log(data)) .catch((error) => console.error("Error fetching data:", error)); }
Explanation:
Clicking the button triggers the fetchData() function, which makes a GET request to the specified URL (in this case, a free API provided by JSONPlaceholder) using the fetch() function. The reply is transformed into JSON format through the utilization of the json() method. If successful, the data (in this case, details of a post) is logged into the console. Otherwise, any errors are caught and logged.
Output:
Web Geolocation API:
Web applications may obtain a user’s device’s geographical position by using the Web Geolocation API. It has features that allow the user to see changes in location over time, access their current position, and get data about latitude, longitude, altitude, direction, speed, and accuracy. With the help of this API, developers may build location-aware web apps like weather predictions, mapping services, and location-based alerts.
Let’s explore some of the key functions and properties along with code examples:
getCurrentPosition():
It fetches the user’s current geographical coordinates, offering details such as latitude, longitude, altitude, precision, direction, velocity, and timestamp.
Example:
//JavaScript navigator.geolocation.getCurrentPosition(successCallback, errorCallback); function successCallback(position) { console.log("Latitude: " + position.coords.latitude); console.log("Longitude: " + position.coords.longitude); } function errorCallback(error) { console.error("Error:", error.message); }
Output:
watchPosition():
Monitors changes in the user’s position over time, continuously updating as the user moves, allowing for real-time tracking in applications.
Example:
//JavaScript let watchID = navigator.geolocation.watchPosition( successCallback, errorCallback ); function successCallback(position) { console.log("Latitude: " + position.coords.latitude); console.log("Longitude: " + position.coords.longitude); } function errorCallback(error) { console.error("Error:", error.message); }
Output:
clearWatch():
Stops watching the user’s position, terminating the ongoing monitoring initiated by ‘clear watch ().’
Example:
//JavaScript navigator.geolocation.clearWatch(watchID)
coords.latitude and coords.longitude:
Express the user’s current position by showcasing latitude and longitude coordinates, offering precise geographical coordinates.
Example:
//JavaScript console.log("Latitude: " + position.coords.latitude); console.log("Longitude: " + position.coords.longitude);
coords.accuracy:
It is a measure of the reliability of the position based on the accuracy of the retrieved position data.
Example:
// JavaScript console.log("Accuracy: " + position.coords.accuracy + " meters");
coords.altitude and coords.altitudeAccuracy:
In this function, the developer receives information regarding the user’s altitude and the accuracy of their measurements, if any.
Example:
// JavaScript console.log("Altitude: " + position.coords.altitude + " meters"); console.log("Altitude Accuracy: " + position.coords.altitudeAccuracy + " meters");
coords.heading:
This indicates the direction in which the user’s device travels, presented in degrees relative to true north.
Example:
// JavaScript console.log("Heading: " + position.coords.heading + " degrees");
coords.speed:
Denotes the velocity of the user’s device motion, usually measured in meters per second.
Example:
// JavaScript console.log("Speed: " + position.coords.speed + " meters per second");
timestamp:
Provides the timestamp indicating when the position data was acquired, facilitating temporal analysis or synchronization with other events.
Example:
// JavaScript console.log("Timestamp: " + position.timestamp);
Conclusion:
In this segment of our series, focusing on crucial Web APIs, we delved into the dynamic functionalities offered by Web Workers, Web Fetch, and Web Geolocation APIs. These APIs expand the horizons of web development, offering solutions for background tasks, network requests, and location-based functionalities. Stay tuned for more insights and practical examples in our ongoing exploration of Web APIs!