What Are Web APIs?

Web APIs (Application Programming Interfaces) are like electrical outlets in a wall. They are standardized interfaces provided by browsers that allow your JavaScript code to access powerful, low-level functionality without you needing to know the complex implementation details. They "plug you in" to features like GPS, the clipboard, or the notification system.

Important Note: Many of these APIs require user permission and only work in a secure context (i.e., over https or on localhost).

Geolocation API: Finding the User

Need to show nearby points of interest or provide location-based services? The Geolocation API is your tool.

The primary method is navigator.geolocation.getCurrentPosition(). It takes up to three arguments: a success callback, an optional error callback, and optional options.

JavaScript


const findMeButton = document.getElementById('find-me');
const locationInfo = document.getElementById('location-info');

findMeButton.addEventListener('click', () => {
  // Check if geolocation is available in the browser
  if (!navigator.geolocation) {
    locationInfo.textContent = 'Geolocation is not supported by your browser.';
    return;
  }

  function success(position) {
    const latitude = position.coords.latitude;
    const longitude = position.coords.longitude;

    locationInfo.textContent = `Latitude: ${latitude}°, Longitude: ${longitude}°`;
    // You could now use these coords to show a map, etc.
  }

  function error() {
    locationInfo.textContent = 'Unable to retrieve your location. Please grant permission.';
  }
  
  // Ask for the user's location
  locationInfo.textContent = 'Locating…';
  navigator.geolocation.getCurrentPosition(success, error);
});

The first time this code runs, the browser will prompt the user for permission to share their location. This is a critical privacy feature.

Clipboard API: Copy & Paste

The modern Clipboard API provides a simple, promise-based way to read from and write to the system clipboard.

Writing to the Clipboard

JavaScript


const copyButton = document.getElementById('copy-btn');
const textToCopy = document.getElementById('shareable-link');

copyButton.addEventListener('click', async () => {
  try {
    // navigator.clipboard.writeText returns a promise
    await navigator.clipboard.writeText(textToCopy.value);
    copyButton.textContent = 'Copied!';
    setTimeout(() => { copyButton.textContent = 'Copy'; }, 2000);
  } catch (err) {
    console.error('Failed to copy text: ', err);
  }
});

This is much simpler and more secure than the older document.execCommand('copy') method.

Notifications API: Getting Attention

Want to alert a user about an important event, like a new message or a completed task, even when they aren't looking at your tab? The Notifications API lets you send native desktop notifications.

This is a two-step process:

  1. Request Permission: You can't send notifications until the user allows it.
  2. Create the Notification: If permission is granted, you can create and dispatch a notification.

JavaScript


const notifyButton = document.getElementById('notify-me');

notifyButton.addEventListener('click', () => {
  // 1. Request permission
  Notification.requestPermission().then(permission => {
    if (permission === 'granted') {
      // 2. If granted, create the notification
      const notification = new Notification('Hello from our Web App!', {
        body: 'This is a sample notification.',
        icon: '/path/to/icon.png' // Optional icon
      });

      // You can also handle clicks on the notification
      notification.onclick = () => {
        // Example: focus the window where the app is running
        window.parent.focus();
        notification.close();
      };

    } else {
      console.log('Notification permission denied.');
    }
  });
});

Like Geolocation, this will trigger a browser prompt asking the user to "Allow" or "Block" notifications from your site.