JavaScript Tutorial
Estimated reading: 4 minutes 206 views

Web APIs in JavaScript โ€“ A Practical Guide to Built-in Browser Features


Introduction โ€“ Why Learn Web APIs?

Web APIs are built into browsers and allow JavaScript to interact with the browser environment, server data, device hardware, and more. They form the bridge between front-end JavaScript and real-world capabilities like local storage, geolocation, and data fetching.

In this guide, you’ll learn:

  • What Web APIs are and why they matter
  • How to use Storage, Fetch, History, Geolocation, Workers, and Form APIs
  • Practical examples to implement in real projects

Topics Covered

Topic Description
Web API OverviewUnderstanding browser-provided APIs
Web Storage APIStore data in browser (Local/Session)
Web WorkersBackground threads for heavy tasks
Fetch APIMake async server requests
Geolocation APIGet user location data
History APIManage session history
Form APIHandle form validation and submission

JavaScript โ€” Web API Overview

What are Web APIs?

Web APIs are browser-provided interfaces that allow your scripts to interact with:

  • The browser (e.g., History, Console)
  • The network (e.g., Fetch, WebSocket)
  • The user device (e.g., Geolocation, Battery API)

These APIs are accessible directly via JavaScript without any third-party libraries.


Web Storage API โ€“ LocalStorage & SessionStorage

LocalStorage

Stores data persistently in key-value format.

localStorage.setItem("theme", "dark");
let theme = localStorage.getItem("theme");
  • Data stays even after the browser is closed.
  • Used for saving preferences, themes, tokens, etc.

SessionStorage

Stores data only during the current session.

sessionStorage.setItem("user", "John");
  • Cleared when the browser/tab is closed.

Web Workers API

What Are Web Workers?

Web Workers allow you to run scripts in background threads, preventing UI blocking.

const worker = new Worker("worker.js");
worker.postMessage("start");

worker.onmessage = function(e) {
  console.log("Message from worker:", e.data);
};

Use for:

  • Heavy computations
  • Real-time processing
  • Keeping UI responsive

Fetch API โ€“ Modern Way to Make Requests

Making a Fetch Request

fetch("https://jsonplaceholder.typicode.com/posts")
  .then(response => response.json())
  .then(data => console.log(data));
  • Promises-based
  • Replaces XMLHttpRequest
  • Cleaner syntax with async/await

Using with async/await

async function loadPosts() {
  const res = await fetch("/api/posts");
  const posts = await res.json();
  console.log(posts);
}

Geolocation API

Get User’s Location

navigator.geolocation.getCurrentPosition((pos) => {
  console.log("Latitude:", pos.coords.latitude);
  console.log("Longitude:", pos.coords.longitude);
});
  • Requires user permission
  • Use HTTPS for production
  • Can be used for maps, location-based features, etc.

History API

Modify the Browser History

history.pushState({ page: 2 }, "Title", "/page2");
  • pushState(), replaceState()
  • window.onpopstate to handle back/forward navigation

Used in single-page applications (SPA) for dynamic routing.


Forms & Validation APIs

Built-in Form Validations

<form onsubmit="return validateForm()" novalidate>
  <input type="email" required />
</form>

JavaScript Validations

document.querySelector("form").addEventListener("submit", (e) => {
  if (!form.checkValidity()) {
    e.preventDefault();
    alert("Please fill all fields correctly.");
  }
});
  • HTML5 input attributes: required, pattern, min, max, type
  • JS properties: .checkValidity(), .validity, .setCustomValidity()

Summary โ€“ Recap & Next Steps

Web APIs make JavaScript incredibly powerful by offering direct access to the browserโ€™s capabilities, device data, and background processing.

Key Takeaways:

  • Use Web Storage for persistent or session-level data
  • Fetch API simplifies network communication
  • Web Workers enable background processing
  • History and Geolocation APIs bring interactive UX features
  • Built-in Form APIs improve validation and submission control

Real-World Relevance:
From saving user settings to fetching APIs and geolocation tracking โ€” Web APIs are essential for building modern, responsive web applications.


FAQs

Q1: Are Web APIs part of JavaScript?

No. Web APIs are provided by the browser, but JavaScript uses them to interact with the browser environment.


Q2: What’s the difference between localStorage and sessionStorage?

localStorage data persists even after the browser is closed; sessionStorage clears when the session ends.


Q3: Can I make API calls without Fetch?

Yes, older methods like XMLHttpRequest exist, but Fetch is the modern, promise-based approach.


Q4: Are Web Workers secure?

Yes. They operate in isolated threads and do not access the DOM directly, improving both performance and security.


Q5: How do I validate forms using Web APIs?

Use HTML5 attributes with form.checkValidity() and setCustomValidity() for robust validation.


Share Now :
Share

๐Ÿงฐ Web APIs

Or Copy Link

CONTENTS
Scroll to Top