The Ultimate Guide to JavaScript Web APIs bilal shafqat

The Ultimate Guide to JavaScript Web APIs

JavaScript Web APIs empower developers to create dynamic, interactive, and feature-rich web applications. These APIs enable seamless interaction between the browser and the system, allowing developers to tap into device capabilities and web functionalities. Here’s a list of essential JavaScript Web APIs with a brief introduction to each:

1. Web Speech API

web speech api

The Web Speech API allows developers to incorporate speech recognition and synthesis capabilities into web applications. It’s perfect for creating voice-controlled interfaces or enabling text-to-speech functionalities.

// Define the text to be spoken
const textToSpeak = "Hello There"; // This is the text that will be converted to speech

// Create a new SpeechSynthesisUtterance object
const utterance = new SpeechSynthesisUtterance(textToSpeak); 
// The SpeechSynthesisUtterance object holds the text and settings for the speech output

// Use the Web Speech API to speak the text
window.speechSynthesis.speak(utterance); 
// This triggers the speech synthesis engine to "speak" the text using the utterance object

 

2. Web Storage API

web storage api bilal shafqat

With the Web Storage API, developers can store data directly in the browser using localStorage and sessionStorage. It’s a lightweight alternative to cookies, providing secure and fast client-side storage for small amounts of data.

// Store data in local storage
localStorage.setItem("key", "value"); 
// The setItem method saves data in the browser's local storage with a specified key ("key") and value ("value")

// Retrieve data from local storage
const storedValue = localStorage.getItem("key"); 
// The getItem method retrieves the value associated with the specified key ("key") from local storage
// The retrieved value is stored in the variable `storedValue`

// Remove data from local storage
localStorage.removeItem("key"); 
// The removeItem method deletes the data associated with the specified key ("key") from local storage

web storage api session storage bilal shafqat

// Store data in local storage
localStorage.setItem("key", "value"); 
// The setItem method saves data in the browser's local storage with a specified key ("key") and value ("value")

// Retrieve data from local storage
const storedValue = localStorage.getItem("key"); 
// The getItem method retrieves the value associated with the specified key ("key") from local storage
// The retrieved value is stored in the variable `storedValue`

// Remove data from local storage
localStorage.removeItem("key"); 
// The removeItem method deletes the data associated with the specified key ("key") from local storage

3. Web Fetch API

web fetch api bilal shafqat

The Fetch API provides a modern way to make HTTP requests. It’s simpler and more flexible than traditional XMLHttpRequest, making it ideal for working with APIs and handling JSON data.

// Fetch data from the specified URL
fetch("http://example.com/movies.json") 
// The fetch function sends a request to the given URL and returns a Promise representing the response

  .then(response => response.json()) 
  // The first `.then` processes the response. The `response.json()` method parses the response body as JSON,
  // returning another Promise that resolves with the parsed JSON data

  .then(data => console.log(data)) 
  // The second `.then` handles the parsed JSON data. Here, it logs the data to the console

  .catch(error => console.error("error", error)); 
  // The `.catch` block handles any errors that occur during the fetch or processing steps,
  // logging the error message to the console

 

4. Web Geolocation API

web geolocation api bilal shafqat

The Geolocation API allows web applications to access the user’s geographical location in real-time. This API is commonly used in map-based apps and location-aware services.

// Use the Geolocation API to get the current position of the device
navigator.geolocation.getCurrentPosition(
  (position) => {
    // This is the success callback that runs if the location is retrieved successfully
    console.log(`Latitude: ${position.coords.latitude}
            Longitude: ${position.coords.longitude}`);
    // The `position` object contains the device's location data
    // `position.coords.latitude` gives the latitude
    // `position.coords.longitude` gives the longitude
    // Both values are logged to the console
  },
  (error) => {
    // This is the error callback that runs if there is an issue retrieving the location
    console.error("Error getting location:", error.message);
    // Logs the error message to the console
  }
);

 

5. Web Canvas API

web canvas api bilal shafqat

The Canvas API enables developers to create graphics, animations, and even games directly in the browser. It uses an HTML <canvas> element and JavaScript to draw shapes, images, and text.

// Create a new <canvas> element
const canvas = document.createElement("canvas"); 
// Dynamically creates a canvas element in the DOM

// Set the canvas width and height
canvas.width = 200; 
// Specifies the width of the canvas in pixels
canvas.height = 100; 
// Specifies the height of the canvas in pixels

// Append the canvas to the body of the document
document.body.appendChild(canvas); 
// Adds the canvas element to the webpage, making it visible

// Get the 2D rendering context for drawing on the canvas
const ctx = canvas.getContext("2d"); 
// The `getContext` method returns a drawing context. Here, "2d" is used for 2D rendering

// Set the fill color for the rectangle
ctx.fillStyle = "blue"; 
// Sets the color to use when filling shapes. In this case, "blue"

// Draw a filled rectangle on the canvas
ctx.fillRect(10, 10, 180, 80); 
// Draws a rectangle starting at (10, 10) with a width of 180 pixels and a height of 80 pixels,
// and fills it with the color specified in `fillStyle` (blue)

 

6. Web Audio API

web audio api bilal shafqat

The Web Audio API is a powerful tool for processing and synthesizing audio in web applications. It’s perfect for creating music apps, sound effects, and even real-time audio visualization tools.

// Create an AudioContext object
const audioContext = new (window.AudioContext || window.webkitAudioContext)(); 
// The AudioContext interface is used to manage and play audio in the browser.
// It provides methods to create and manipulate audio content.
// The fallback `window.webkitAudioContext` ensures compatibility with older browsers.

// Create an oscillator node
const oscillator = audioContext.createOscillator(); 
// An oscillator generates periodic waveforms, such as sine waves, for audio signals.
// This oscillator will produce the sound.

// Set the frequency of the oscillator
oscillator.frequency.setValueAtTime(440, audioContext.currentTime); 
// Sets the frequency of the oscillator to 440 Hz (the pitch of the "A4" musical note).
// `audioContext.currentTime` ensures the frequency change starts immediately.

// Connect the oscillator to the audio destination
oscillator.connect(audioContext.destination); 
// Connects the oscillator to the destination (usually the system speakers) so the sound can be heard.

// Start the oscillator
oscillator.start(); 
// Begins playing the sound immediately.

// Stop the oscillator after 1 second
oscillator.stop(audioContext.currentTime + 1); 
// Stops the sound 1 second after the current time.

 

7. WebSockets API

web sockets api

The WebSockets API enables real-time, two-way communication between a client and a server. It’s ideal for applications like chat apps, live notifications, and multiplayer games.

// Create a new WebSocket connection to the specified URL
const socket = new WebSocket("wss://example.com/socket"); 
// The WebSocket constructor establishes a connection to the WebSocket server at the specified URL.
// The `wss://` prefix indicates a secure WebSocket connection (encrypted).

// Event listener for the "open" event
socket.addEventListener("open", () => {
  // This event is triggered when the WebSocket connection is successfully established.
  socket.send(`Hello, Server!`); 
  // Sends a message (`Hello, Server!`) to the server immediately after the connection opens.
});

// Event listener for the "message" event
socket.addEventListener("message", (event) => {
  // This event is triggered when a message is received from the server.
  console.log("Received:", event.data); 
  // Logs the message content (`event.data`) to the console.
});

// Event listener for the "close" event
socket.addEventListener("close", () => {
  // This event is triggered when the WebSocket connection is closed by either the client or the server.
  console.log("Connection closed."); 
  // Logs a message indicating the connection has been closed.
});

8. Web IndexedDB API

web indexedDB api bilal shafqat

IndexedDB is a low-level API for client-side storage of large amounts of structured data. It allows for complex querying and indexing, making it perfect for offline web apps and caching data.

// Define the name and version of the IndexedDB database
const dbName = "InstagramPostsDB"; 
// The name of the database to open or create.

const dbVersion = 1; 
// The version of the database. This is useful for handling database schema upgrades.

// Open a connection to the IndexedDB database
const request = indexedDB.open(dbName, dbVersion); 
// This initiates a request to open the database with the specified name and version.
// If the database does not exist, it will be created.
// If the version number is higher than the current version, the `onupgradeneeded` event will trigger.

// Event listener for errors during the database opening process
request.onerror(() => {
  // This event is triggered if there is an error during the opening process.
  console.error("Error opening database.");
});

// Event listener for database upgrades (e.g., creating or modifying object stores)
request.onupgradeneeded((event) => {
  // This event is triggered when the database needs to be upgraded.
  // For example, if the database is being created for the first time or if the version number increases.
  const db = event.target.result; // The database instance
  console.log("Upgrading database...");
  // Add logic here to create or modify object stores, indexes, etc.
});

// Event listener for successful database opening
request.onsuccess((event) => {
  // This event is triggered when the database is successfully opened.
  const db = event.target.result; // The database instance
  console.log("Database opened successfully:", db);
  // You can now interact with the database (e.g., add, retrieve, update, or delete data).
});

 

9. Web File API

web file api bilal shafqat

The File API enables web applications to interact with local files selected by the user. It’s often used for file uploads, previews, or editing files directly in the browser.

<!-- File input element for selecting an image -->
<input type="file" id="imageInput" accept="image/*">
<!-- Button to trigger the uploadPost function -->
<button onclick="uploadPost()">Upload Post</button>

<script>
  // Function to handle file selection and log the file details
  function uploadPost() {
    // Access the file selected in the input element with id "imageInput"
    const file = document.getElementById("imageInput").files[0];
    // The `files` property is a FileList object. `[0]` gets the first (and usually only) selected file.

    console.log("Selected file:", file);
    // Logs the selected file object to the console. This includes file metadata like name, size, and type.
  }
</script>

 

10. Web Notification API

web notification api bilal shafqat

The Notification API allows web apps to send notifications to the user, even when the browser is minimized. It’s a great way to engage users with updates, reminders, or alerts.

// Request the user's permission to display notifications
Notification.requestPermission().then((permission) => {
  // This Promise resolves with the user's choice: "granted", "denied", or "default"

  if (permission === "granted") {
    // If the user grants permission, create and display a new notification
    new Notification("Hello, World");
    // The Notification constructor creates a new notification with the specified title ("Hello, World").
    // This will display a notification on the user's device if the browser supports it.
  } else {
    // Handle cases where permission is denied or not granted
    console.log("Notification permission not granted:", permission);
  }
});

 

11. Web Workers API

web workers api bilal shafqat

Web Workers enable running JavaScript code in the background, without blocking the main thread. This API is crucial for improving performance in applications that require heavy computations.

// Create a new Web Worker instance
const worker = new Worker("worker.js");
// The Worker constructor takes the URL of the worker script ("worker.js").
// This script will run in a separate thread, allowing the main script to stay responsive.

// Send a message to the worker
worker.postMessage("Hello from main script");
// The `postMessage` method sends data to the worker.
// The message ("Hello from main script") can be any serializable object, such as a string, number, array, or JSON object.

 

12. Web Mutation Observer API

Web Mutation Observer API bilal shafqat

The Mutation Observer API provides a way to watch for changes to the DOM. It’s a powerful tool for observing and responding to dynamic content updates.

13. Web Pointer Lock API

web pointer lock api bilal shafqat

The Pointer Lock API is used for locking the mouse pointer to a specific element. It’s often employed in immersive web applications, such as first-person games or 3D simulations.

// Get the DOM element by its ID
const element = document.getElementById("yourElementId");
// Replace "yourElementId" with the ID of the element you want to enable pointer lock on.

// Request pointer lock for the element
element.requestPointerLock();
// This method requests the browser to lock the pointer (mouse cursor) to the element.
// Once the pointer is locked, the mouse cursor will be hidden, and mouse movement will only be reported as relative changes.
// This is commonly used in applications like 3D games or drawing tools.

 

14. Web Battery Status API

web battery status api bilal shafqat

The Battery Status API provides information about the device’s battery level and charging status. This API helps developers optimize app behavior based on battery usage.

// Use the Battery Status API to get the battery information
navigator.getBattery().then((battery) => {
  // The `getBattery()` method returns a Promise that resolves to a BatteryManager object.

  // Log the current battery level (as a percentage)
  console.log("Battery Level:", battery.level * 100 + "%");
  // The `battery.level` property gives the battery charge level as a decimal between 0 (empty) and 1 (full).
  // Multiplying by 100 converts it to a percentage.

  // Log whether the device is charging
  console.log("Charging:", battery.charging ? "Yes" : "No");
  // The `battery.charging` property is a boolean that indicates if the battery is charging.
});

 

15. Web Gamepad API

Web Gamepad API

The Gamepad API enables support for game controllers, allowing developers to create immersive gaming experiences directly in the browser.

// Listen for when a gamepad is connected to the browser
window.addEventListener("gamepadconnected", (event) => {
  console.log("Gamepad connected:", event.gamepad.id);
  // Logs a message when a gamepad is connected, including its ID.
  // The `event.gamepad` object provides information about the connected gamepad.
});

// Listen for when a gamepad is disconnected from the browser
window.addEventListener("gamepaddisconnected", (event) => {
  console.log("Gamepad disconnected:", event.gamepad.id);
  // Logs a message when a gamepad is disconnected, including its ID.
});

16. Web Device Orientation and Motion API

Web Device Orientation and Motion API

This API provides access to the device’s accelerometer and gyroscope data. It’s commonly used for motion-based interactions, such as tilting a device to control a game.

// Listen for device orientation changes (e.g., the tilt of the device)
window.addEventListener("deviceorientation", (event) => {
  console.log("Device Orientation:", event.alpha, event.beta, event.gamma);
  // `event.alpha`, `event.beta`, and `event.gamma` provide the orientation of the device:
  // - `alpha`: The rotation around the Z-axis (compass heading), in degrees.
  // - `beta`: The rotation around the X-axis (tilt forward/backward), in degrees.
  // - `gamma`: The rotation around the Y-axis (tilt left/right), in degrees.
  // These values represent the orientation of the device relative to the Earth's axes.
});

// Listen for device motion events (e.g., acceleration of the device)
window.addEventListener("devicemotion", (event) => {
  console.log(
    "Device Motion:",
    event.acceleration.x,
    event.acceleration.y,
    event.acceleration.z
  );
  // `event.acceleration` provides the acceleration of the device along the X, Y, and Z axes:
  // - `x`: Acceleration along the X-axis (left/right).
  // - `y`: Acceleration along the Y-axis (up/down).
  // - `z`: Acceleration along the Z-axis (forward/backward).
  // These values represent the linear acceleration in meters per second squared (m/s²).
});

 

17. Web Push API

Web Device Orientation and Motion API bilal shafqat

The Push API enables web applications to receive push notifications from a server, even when the application is not active. It’s a great tool for re-engaging users with updates or promotions.

// Check if the PushManager API is supported by the browser
if ("PushManager" in window) {
  // Request permission from the user to send notifications
  Notification.requestPermission().then((permission) => {
    // This Promise resolves with the user's choice: "granted", "denied", or "default".

    if (permission === "granted") {
      // If the user grants permission, you can proceed with subscription logic
      console.log("Notification permission granted.");
      // Subscription logic goes here (e.g., subscribing to a push service).
    } else {
      // Handle cases where the user denies or dismisses the permission request
      console.log("Notification permission not granted:", permission);
    }
  });
} else {
  // The PushManager API is not supported by the browser
  console.log("Push notifications are not supported in this browser.");
}

 

18. Web Payment Request API

Web Payment Request API

The Payment Request API streamlines the checkout process by integrating payment options directly into the browser. It enhances the user experience and reduces friction during transactions.

// Define the supported payment methods
const supportedInstruments = [{ supportedMethods: "basic-card" }];
// This specifies the payment methods supported. In this case, "basic-card" represents traditional credit/debit card payments.

// Define the payment details
const paymentDetails = {
  total: { 
    label: "Total", 
    amount: { currency: "USD", value: "10.00" } 
    // Specifies the total amount to be charged in USD, with a value of $10.00
  },
};

// Create a new PaymentRequest instance
const paymentRequest = new PaymentRequest(supportedInstruments, paymentDetails);
// The PaymentRequest constructor takes two arguments:
// - The payment methods (`supportedInstruments`)
// - The payment details (`paymentDetails`)

// Show the payment request dialog to the user
paymentRequest.show()
  .then((paymentResponse) => {
    // This callback is triggered after the user interacts with the payment dialog (e.g., approving or canceling payment).

    console.log("Payment successful:", paymentResponse); 
    // Log the payment response for debugging purposes.

    return paymentResponse.complete("success");
    // Marks the payment process as complete. The "success" argument indicates the transaction was successful.
  })
  .catch((error) => {
    // Handle any errors during the payment process (e.g., user cancels or technical issues)
    console.error("Payment failed:", error);
  });

 

Conclusion

JavaScript Web APIs offer developers endless possibilities to enhance the functionality and interactivity of their applications. By leveraging these APIs, you can create innovative, user-friendly web experiences.

Leave A Comment