Skip to content
Tutorials Center
My learning

Topics

Lesson 109 of 156 ยท Browser APIs

Geolocation, Notifications and Clipboard APIs

Use permission-based browser APIs safely - geolocation, notifications and the async clipboard - with feature detection, the Permissions API, error codes and graceful fallbacks.

Some browser features touch things that belong to the user: where they are, their screen's notification area, the text they copied. A web page cannot just take them. The browser asks the user first, remembers the answer, and your code has to cope with the answer being no. Three APIs show the pattern very well: Geolocation (where am I?), Notifications (show a message outside the page) and the Clipboard API (copy and paste from code).

They look different, but they share rules: they only work on secure origins (HTTPS or localhost), they usually need a user gesture such as a click, they return promises or callbacks that can fail, and none of them can be assumed to exist. In this lesson you will learn each API, the shared permission model, and how to write code that still behaves when access is blocked.

These editors run in a sandbox. The preview frames on this site have no real origin and deliberately block device features. Geolocation, notification permission and the clipboard will normally be denied here, and the runnable examples are written so you can see exactly those failure paths. Copy the successful versions into a page served from https:// or http://localhost to see the real prompts.

The shared permission model

All three APIs follow the same life cycle:

  1. Detect the feature. Check that the object exists ("geolocation" in navigator, "Notification" in window, navigator.clipboard) before using it.
  2. Ask at the right moment. Request permission in response to a click, not on page load. A prompt that appears before the user understands why is usually refused, and a refusal can be permanent.
  3. Handle every outcome. The user may allow, deny, dismiss the prompt, or have blocked the feature already. The device may also fail (no GPS signal) even when permission was given.
  4. Offer a fallback. A "type your city" box, a visible "Copy failed, press Ctrl+C" message, an in-page banner instead of a notification.

The Permissions API lets you ask what the current state is without triggering a prompt:

JavaScript
// Read-only: runs in a real page
const status = await navigator.permissions.query({ name: "geolocation" });
console.log(status.state);          // "granted", "denied" or "prompt"
status.addEventListener("change", () => console.log("Now:", status.state));

"granted" means you can go ahead, "prompt" means the browser will ask, and "denied" means asking again will do nothing: tell the user how to re-enable the feature in the browser's site settings. Not every permission name is supported in every browser, so wrap query() in a try/catch.

Geolocation

navigator.geolocation gives you the device's position, from GPS, Wi-Fi or the network. It uses callbacks rather than promises:

JavaScript
// Read-only: runs in a real page
navigator.geolocation.getCurrentPosition(
  (position) => {
    const { latitude, longitude, accuracy } = position.coords;
    console.log(`You are near ${latitude}, ${longitude} (within ${accuracy} m)`);
  },
  (error) => console.log("Could not get location:", error.code, error.message),
  { enableHighAccuracy: false, timeout: 10_000, maximumAge: 60_000 },
);

The position's coords holds latitude, longitude (degrees), accuracy (meters), and sometimes altitude, speed and heading. The three options are:

  • enableHighAccuracy: ask for GPS-quality data. Slower and drains the battery, so leave it off unless you need it.
  • timeout: how long to wait, in milliseconds, after the user has answered the prompt.
  • maximumAge: accept a cached position up to this old (in milliseconds) instead of measuring again.

The error object has a code: 1 = permission denied, 2 = position unavailable, 3 = timeout. For continuous tracking, watchPosition() calls your function every time the position changes and returns an id you stop with clearWatch(id).

Callbacks are awkward, so wrap them in a promise once and use await everywhere else. This version also turns the numeric codes into friendly messages. It runs for real below; in the sandbox expect the "denied" branch:

JS A promise wrapper around geolocation

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Whatever the result, the page does not break: it falls back to asking for a city. That is the habit to build.

Working with coordinates

Once you have a position, you often compare it with places. The haversine formula gives the great-circle distance between two latitude/longitude pairs. This example needs no permission, so it always runs:

JS Distance between two places

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Treat location as sensitive personal data: ask only when a feature needs it, say why, never log it carelessly, and don't send it to a server unless the user understands that.

Notifications

The Notifications API shows a system notification outside the page. Permission is stored in Notification.permission, which is "default" (not asked yet), "granted" or "denied":

JavaScript
// Read-only: runs in a real page
button.addEventListener("click", async () => {
  if (!("Notification" in window)) return;

  const permission = await Notification.requestPermission();
  if (permission !== "granted") return;

  const notification = new Notification("Build finished", {
    body: "All 128 tests passed.",
    tag: "build-status",          // a new notification with the same tag replaces the old one
  });
  notification.onclick = () => window.focus();
});

Always call requestPermission() from a click handler. The result is a promise (older browsers used a callback, but you can ignore that now). Useful options are body, icon, tag (to replace rather than stack notifications) and silent.

Two limits to know:

  • Notifications from a page only show while the page is open. To notify a user whose tab is closed you need a service worker and the Push API (see Service Workers and the Cache API); on those pages you call registration.showNotification() instead of new Notification().
  • Mobile browsers often refuse the Notification constructor and expect the service-worker route.

Because a permission request is a request for the user's attention, use it sparingly: ask after the user has done something that makes a notification valuable (for instance, after starting a long export), and never more than once.

The code below uses an in-page toast as the fallback when notifications are not available. Run it: in the sandbox, notifications are blocked, so you see the fallback:

JS Notification with a fallback

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The Clipboard API

The old way to copy text was document.execCommand("copy") on a hidden input. It still exists but is deprecated. The modern async clipboard is navigator.clipboard:

JavaScript
// Read-only: runs in a real page
copyButton.addEventListener("click", async () => {
  try {
    await navigator.clipboard.writeText(codeBlock.textContent);
    copyButton.textContent = "Copied!";
  } catch (error) {
    copyButton.textContent = "Press Ctrl+C to copy";
  }
});
  • writeText(text) and readText() handle plain text. write([new ClipboardItem({...})]) and read() handle richer data such as images and HTML.
  • Writing usually works when it happens in a user gesture (a click) on a focused, secure page. No prompt is needed in most browsers.
  • Reading is more sensitive, because the clipboard may hold a password. Browsers ask permission or require an explicit paste action, and some only allow it while the page is focused.
  • For pasting into your page, you do not need readText() at all: listen for the paste event and read event.clipboardData.getData("text"), which works without any permission because the user pressed Ctrl+V.

The next demo tries to copy and handles every outcome. In the sandbox it fails, which is exactly what real users with a blocked clipboard would see:

JS Copy to the clipboard with a fallback

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Other small device APIs

The same detect, ask, handle-errors, fall-back pattern applies to many others: the Vibration API (navigator.vibrate(200), mostly Android), the Web Share API (navigator.share({ title, url }) to open the system share sheet, which requires a click), screen orientation, battery (removed from several browsers for privacy reasons) and the camera/microphone through getUserMedia(), covered in Media and Speech APIs. Check before using each:

JS Which features exist here?

Press Run (or Ctrl + Enter) to see the console output here.

No output.

"Exists" does not mean "allowed": a feature can be present and still blocked, as the earlier examples showed.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. When should you call Notification.requestPermission()?

    Prompts shown without context are often refused permanently. Ask after a click or similar action that explains the benefit, and only once.
  2. 2. In a geolocation error callback, what does error.code 1 mean?

    Code 1 is PERMISSION_DENIED, 2 is POSITION_UNAVAILABLE and 3 is TIMEOUT.
  3. 3. What does navigator.permissions.query() report for geolocation when the user has blocked location for your site?

    The Permissions API reports granted, denied or prompt without asking the user. Once denied, you must explain how to change the site setting.
  4. 4. Which is the most reliable way to read text the user pastes into your page?

    The paste event runs because the user pressed paste, so event.clipboardData is available without extra permission. readText() is more restricted.
  5. 5. Why should geolocation, notifications and clipboard code always include a fallback?

    Permission-based features can fail in several ways. A fallback (typing a city, a visible message, an in-page toast) keeps the page useful.

Summary

  • Permission-based APIs need a secure context, usually a user gesture, and always a plan for refusal.
  • Detect the feature, ask at a sensible moment, handle every outcome, and provide a fallback.
  • Geolocation: getCurrentPosition() and watchPosition() use callbacks (wrap them in a promise); error codes are 1 denied, 2 unavailable, 3 timeout.
  • Notifications: Notification.requestPermission() from a click, then new Notification(); closed-tab notifications need a service worker.
  • Clipboard: navigator.clipboard.writeText() in a click handler; use the paste event for incoming pasted data.
  • Query the state without prompting using navigator.permissions.query().

Next, store larger amounts of structured data in the browser: IndexedDB for Client-Side Storage.