Skip to main content

Front-End Development

Understanding JavaScript Web APIs: Part 3

Istock 1435220822

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:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<buttononclick="startWorker()">Start Worker</button>
<button onclick="startWorker()">Start Worker</button>
<button onclick="startWorker()">Start Worker</button>

JavaScript:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
let worker;
functionstartWorker(){
if(typeof Worker !== "undefined"){
if(typeof worker == "undefined"){
worker = newWorker("worker.js");
}
worker.onmessage = function(event){
console.log("Message received from worker: " + event.data);
};
}else{
console.log("Web Workers not supported in this browser.");
}
}
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."); } }
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:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
setInterval(()=>{
postMessage("Hello from the worker!");
}, 1000);
setInterval(() => { postMessage("Hello from the worker!"); }, 1000);
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:

Worker

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:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<button onclick="fetchData()">Fetch Data</button>
<button onclick="fetchData()">Fetch Data</button>
<button onclick="fetchData()">Fetch Data</button>

JavaScript:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
functionfetchData(){
fetch("https://jsonplaceholder.typicode.com/posts/1")
.then((response)=> response.json())
.then((data)=>console.log(data))
.catch((error)=>console.error("Error fetching data:", error));
}
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)); }
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:

Fetchapi

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:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
//JavaScript
navigator.geolocation.getCurrentPosition(successCallback, errorCallback);
functionsuccessCallback(position){
console.log("Latitude: " + position.coords.latitude);
console.log("Longitude: " + position.coords.longitude);
}
functionerrorCallback(error){
console.error("Error:", error.message);
}
//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); }
//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:

Getcurrentposition

watchPosition():

Monitors changes in the user’s position over time, continuously updating as the user moves, allowing for real-time tracking in applications.

Example:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
//JavaScript
let watchID = navigator.geolocation.watchPosition(
successCallback,
errorCallback
);
functionsuccessCallback(position){
console.log("Latitude: " + position.coords.latitude);
console.log("Longitude: " + position.coords.longitude);
}
functionerrorCallback(error){
console.error("Error:", error.message);
}
//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); }
//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:

Watch

clearWatch():

Stops watching the user’s position, terminating the ongoing monitoring initiated by ‘clear watch ().’

Example:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
//JavaScript
navigator.geolocation.clearWatch(watchID)
//JavaScript navigator.geolocation.clearWatch(watchID)
//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:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
//JavaScript
console.log("Latitude: " + position.coords.latitude);
console.log("Longitude: " + position.coords.longitude);
//JavaScript console.log("Latitude: " + position.coords.latitude); console.log("Longitude: " + position.coords.longitude);
//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:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
// JavaScript
console.log("Accuracy: " + position.coords.accuracy + " meters");
// JavaScript console.log("Accuracy: " + position.coords.accuracy + " meters");
// 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:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
// JavaScript
console.log("Altitude: " + position.coords.altitude + " meters");
console.log("Altitude Accuracy: " + position.coords.altitudeAccuracy + " meters");
// JavaScript console.log("Altitude: " + position.coords.altitude + " meters"); console.log("Altitude Accuracy: " + position.coords.altitudeAccuracy + " meters");
// 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:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
// JavaScript
console.log("Heading: " + position.coords.heading + " degrees");
// JavaScript console.log("Heading: " + position.coords.heading + " degrees");
// 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:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
// JavaScript
console.log("Speed: " + position.coords.speed + " meters per second");
// JavaScript console.log("Speed: " + position.coords.speed + " meters per second");
// 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:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
// JavaScript
console.log("Timestamp: " + position.timestamp);
// JavaScript console.log("Timestamp: " + position.timestamp);
// 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!

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Sufiyan Akbani

Sufiyan Akbani is an Associate Technical Consultant at Perficient, with a keen interest in UI development. With over 2 years of experience in this field, Sufiyan is passionate about exploring the latest trends and emerging technologies in UI and front-end development. He finds joy in watching fiction movies and immersing himself in nature by hiking in hill stations during his free time.

More from this Author

Follow Us