HTML APIs

An API (Application Programming Interface) is a set of tools and rules that lets your web page communicate with something — a browser feature, an external service, or another piece of software. HTML5 introduced many powerful browser APIs that give web pages abilities previously reserved for desktop apps. This topic surveys the most important ones.

What an API Is — In Simple Terms

Visual Diagram — API as a Waiter

You (web page)    →   API (waiter)   →   Service (kitchen/browser feature)
     |                    |                          |
"I want the         "Table 5 wants               Processes
 user's location"    the location"                request
     |                    |                          |
     ←────────────────────←──────────────────────────
     Receives coordinates back

You do not need to know how the browser determines location — you just call the API and get the result back.

The Browser API Landscape

Visual Diagram — HTML5 API Categories

                HTML5 Browser APIs
                      |
     +────────────────+────────────────+
     |                |                |
  Device           Storage          Media
  APIs              APIs             APIs
     |                |                |
  Geolocation      localStorage     MediaDevices
  Vibration        IndexedDB        WebRTC
  Battery          Cache API        Web Audio
  DeviceOrientation                 MediaRecorder
     |
  Communication         Rendering
  APIs                  APIs
     |                    |
  Fetch API            Canvas API
  WebSockets           WebGL
  Server-Sent Events   SVG
  WebRTC               CSS Paint

The Fetch API

The Fetch API loads data from URLs — your own server, a third-party API, or any public data source. It replaced the older XMLHttpRequest method and uses a simpler, cleaner syntax with promises.

<p id="result">Loading...</p>

<script>
  fetch("https://api.example.com/users/1")
    .then(function(response) {
      return response.json();    // parse the JSON response
    })
    .then(function(user) {
      document.getElementById("result").textContent =
        "Name: " + user.name + " | Email: " + user.email;
    })
    .catch(function(error) {
      document.getElementById("result").textContent = "Error: " + error.message;
    });
</script>

Fetch with POST — Sending Data

fetch("https://api.example.com/messages", {
  method: "POST",
  headers: {
    "Content-Type": "application/json"
  },
  body: JSON.stringify({
    title: "Hello",
    body: "This is a test message"
  })
})
.then(response => response.json())
.then(data => console.log("Created:", data));

The Web Notifications API

The Notifications API lets your web page send desktop notifications — messages that appear outside the browser window, even when the page is not visible.

<button onclick="showNotification()">Get Notified</button>

<script>
  function showNotification() {
    // Request permission first
    Notification.requestPermission().then(function(permission) {
      if (permission === "granted") {
        new Notification("New Message!", {
          body: "You have a new message from Alice.",
          icon: "favicon.png"
        });
      }
    });
  }
</script>

Visual Diagram — Notification Flow

1. Page calls Notification.requestPermission()
2. Browser shows: "Allow notifications from example.com?" [Allow] [Block]
3. User clicks Allow → permission = "granted"
4. Page creates: new Notification("Title", { body: "..." })
5. OS shows desktop notification popup in corner of screen

The Clipboard API

The Clipboard API lets your page read from and write to the user's clipboard — the equivalent of Ctrl+C and Ctrl+V.

<button onclick="copyText()">Copy Code</button>
<p id="status"></p>

<script>
  function copyText() {
    const textToCopy = "npm install estudy247";

    navigator.clipboard.writeText(textToCopy)
      .then(function() {
        document.getElementById("status").textContent = "Copied!";
      })
      .catch(function(err) {
        document.getElementById("status").textContent = "Failed to copy";
      });
  }
</script>

The MediaDevices API — Camera and Microphone

The MediaDevices API gives web pages access to the device's camera and microphone, after the user grants permission.

<video id="preview" autoplay style="width:300px;"></video>
<button onclick="startCamera()">Open Camera</button>

<script>
  function startCamera() {
    navigator.mediaDevices.getUserMedia({ video: true, audio: false })
      .then(function(stream) {
        document.getElementById("preview").srcObject = stream;
      })
      .catch(function(error) {
        console.log("Camera access denied:", error.message);
      });
  }
</script>

The browser asks permission before granting access. This API powers video call web apps, QR code scanners, and photo capture tools.

The Vibration API

The Vibration API makes a mobile device vibrate. Useful for games, form validation alerts, and notification feedback.

<script>
  // Vibrate for 200 milliseconds
  navigator.vibrate(200);

  // Vibrate in a pattern: on 100ms, off 50ms, on 200ms
  navigator.vibrate([100, 50, 200]);

  // Stop vibrating
  navigator.vibrate(0);
</script>

The Page Visibility API

The Page Visibility API tells you whether the user is currently looking at your page — the tab is active — or has switched to another tab or minimized the window.

<script>
  document.addEventListener("visibilitychange", function() {
    if (document.hidden) {
      console.log("User switched away — pause video, stop animations");
    } else {
      console.log("User came back — resume video");
    }
  });
</script>

The Fullscreen API

The Fullscreen API expands any element to fill the entire screen — useful for video players, presentations, and games.

<video id="myVideo" src="lesson.mp4" controls></video>
<button onclick="goFullscreen()">Fullscreen</button>

<script>
  function goFullscreen() {
    const video = document.getElementById("myVideo");

    if (video.requestFullscreen) {
      video.requestFullscreen();
    }
  }

  // Exit fullscreen
  function exitFullscreen() {
    if (document.exitFullscreen) {
      document.exitFullscreen();
    }
  }
</script>

The History API

The History API lets JavaScript modify the browser's URL and navigation history without reloading the page. Single Page Applications (SPAs) like React apps use this to change the URL as users navigate sections.

<script>
  // Add a new entry to history without reloading
  history.pushState({ page: "about" }, "About", "/about");

  // Replace current entry without adding a new one
  history.replaceState({ page: "home" }, "Home", "/");

  // Listen for back/forward button navigation
  window.addEventListener("popstate", function(event) {
    console.log("Navigated to:", event.state);
  });
</script>

The ResizeObserver API

The ResizeObserver API watches an element and fires a callback whenever its size changes — useful for responsive components that need to react to their own container size.

<div id="box" style="width:300px; resize:both; overflow:auto; border:1px solid #ccc; padding:10px;">
  Resize me!
</div>
<p id="sizeInfo"></p>

<script>
  const observer = new ResizeObserver(function(entries) {
    for (const entry of entries) {
      const w = Math.round(entry.contentRect.width);
      const h = Math.round(entry.contentRect.height);
      document.getElementById("sizeInfo").textContent = w + " × " + h + " px";
    }
  });

  observer.observe(document.getElementById("box"));
</script>

The IntersectionObserver API

The IntersectionObserver API fires a callback when an element enters or leaves the visible viewport. Used for lazy loading images, infinite scroll, and animation triggers.

<img id="lazyImg" data-src="large-photo.jpg" src="placeholder.jpg" alt="Photo">

<script>
  const observer = new IntersectionObserver(function(entries) {
    entries.forEach(function(entry) {
      if (entry.isIntersecting) {
        const img = entry.target;
        img.src = img.dataset.src;   // load the real image
        observer.unobserve(img);     // stop watching this image
      }
    });
  });

  observer.observe(document.getElementById("lazyImg"));
</script>

API Quick Reference

API                    What It Does
---------------------  -------------------------------------------
Fetch API              Load data from URLs (HTTP requests)
Geolocation API        Get user's GPS/network location
Web Storage API        Save data in browser (localStorage/sessionStorage)
Notifications API      Send desktop/OS notifications
Clipboard API          Read and write the system clipboard
MediaDevices API       Access camera and microphone
Vibration API          Make device vibrate (mobile)
Page Visibility API    Detect if user switched tabs
Fullscreen API         Expand an element to full screen
History API            Change URL without page reload
ResizeObserver         Watch element size changes
IntersectionObserver   Watch element visibility in viewport
Canvas API             Draw graphics with JavaScript
Web Workers API        Run JavaScript in background thread
SSE / EventSource      Receive server-pushed real-time events

Each API solves a specific problem. You do not need to learn all of them at once — learn the ones relevant to the project you are building. The browser APIs together make the web a powerful application platform, capable of tasks that once required native apps.

Leave a Comment

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