Skip to content
Tutorials Center
My learning

Topics

Lesson 100 of 122 ยท Web APIs

Web Share, Clipboard and Notifications APIs

Share content through the system share sheet, copy and paste with the async Clipboard API, and ask for Notification permission the right way, with fallbacks.

Three small browser APIs connect your page to the world around it. The Web Share API opens the device's own share sheet, so visitors can send a link to any app they have installed. The Clipboard API lets a button copy text for the user, or read what they chose to paste. The Notifications API shows short messages in the operating system, outside the browser window.

All three touch something personal (the user's apps, their clipboard, their attention), so they follow the rules from Introduction to Web APIs: they work only in secure contexts, they usually need a recent user gesture such as a click, and some of them ask for permission. In this lesson you will meet each one, see how it fails, and write the fallbacks that keep your page useful when it does.

The editors on this site run in a sandbox that blocks these features. So the examples handle failure on purpose, and the code that would work on a real page is shown in read-only blocks.

Feature detection comes first

Never assume an API exists. Check for it, and design the page so it still works without it:

JavaScript
const canShare = typeof navigator.share === 'function';
const canCopy = Boolean(navigator.clipboard && navigator.clipboard.writeText);
const canNotify = 'Notification' in window;

A good pattern is progressive enhancement: ship a normal link or a visible text field, and reveal the "Share" or "Copy" button only when the API is available. Run the next example to see what your browser reports.

What does this browser offer?

The Web Share API

navigator.share() opens the system share sheet. On a phone that means Messages, Mail, chat apps and more; on desktop it depends on the operating system and browser. You pass an object with some of these fields:

Field Meaning
title A title, used by some targets such as email subjects.
text A short description.
url The address to share.
files An array of File objects, for example an image. Check with canShare() first.

share() returns a promise. It resolves when the user finishes sharing and rejects when something goes wrong. The most common rejection is an AbortError, which only means the user closed the sheet. That is not a failure, so do not show an error.

JavaScript
const shareButton = document.getElementById('share');

shareButton.addEventListener('click', async () => {
  const data = {
    title: 'Fast-Loading HTML',
    text: 'A practical guide to making pages load quickly.',
    url: location.href,
  };

  try {
    await navigator.share(data);
  } catch (error) {
    if (error.name !== 'AbortError') {
      console.error('Share failed:', error);
    }
  }
});

Rules to remember:

  • It must be called from a user gesture (a click or tap), never on page load.
  • The page must be in a secure context.
  • Inside an iframe, the parent must allow it with allow="web-share".
  • Support is wide on phones and tablets, patchy on desktop browsers, so always have a fallback.
  • Use navigator.canShare(data) to check whether the data (especially files) can be shared before showing the button.

A share button with a fallback

If sharing is not possible, fall back to something that always works: a visible link the user can copy, or a few ordinary links to social sites. The next example builds the data, decides which route to use, and shows the result. In this sandbox it takes the fallback route.

Share with a fallback

The async Clipboard API

The clipboard holds what the user last copied. The modern interface is navigator.clipboard, an object whose methods all return promises, so a slow or refused operation never freezes the page.

Method What it does
writeText(text) Puts plain text on the clipboard.
readText() Reads plain text from the clipboard.
write(items) Writes rich data such as images or HTML, using ClipboardItem objects.
read() Reads rich data.

Copying is the easy and common case. It needs a secure context and, in most browsers, a click or similar gesture, and it does not show a permission prompt:

JavaScript
async function copyText(text) {
  try {
    await navigator.clipboard.writeText(text);
    return true;
  } catch {
    return false;
  }
}

copyButton.addEventListener('click', async () => {
  const ok = await copyText(codeElement.textContent);
  copyButton.textContent = ok ? 'Copied!' : 'Press Ctrl+C to copy';
});

Reading is more sensitive, because a clipboard can contain a password or a private message. readText() therefore needs the user's permission, which the browser asks for in its own way: Chrome and Edge ask for the "clipboard-read" permission, while Safari and Firefox show a small Paste button the user must click. Your code should handle refusal and keep a normal text field available. Often a plain paste event is enough and needs no permission, because it only fires when the user pastes on purpose:

JavaScript
document.getElementById('editor').addEventListener('paste', (event) => {
  const text = event.clipboardData.getData('text/plain');
  event.preventDefault();
  insertAtCursor(text.trim());
});

The copy, cut and paste events also fire when users use their own shortcuts, so you can adapt what ends up on the clipboard, for example to append a source link.

Never quietly overwrite the clipboard. Copying should always happen because the user pressed something that clearly says "Copy".

A copy button that handles failure

This example tries the modern API, then an old technique, then explains what to do. It prints which route succeeded, so you can see the sandbox rules at work.

A defensive copy button

document.execCommand('copy') is the deprecated technique. It is included only as a safety net for old browsers. Prefer the Clipboard API wherever it exists.

The Notifications API

The Notifications API shows a message through the operating system, so it can reach the user even when your tab is in the background. That power makes it easy to abuse, and browsers guard it carefully.

stateDiagram-v2
    state "default (not asked)" as Undecided
    state "granted" as Granted
    state "denied" as Denied
    [*] --> Undecided: first visit
    Undecided --> Granted: user clicks Allow
    Undecided --> Denied: user clicks Block
    Denied --> Undecided: user resets site settings
    Granted --> Undecided: user resets site settings

Notification permission starts as "default" and only the user, through the browser, can change it.

The permission is stored per site and read from Notification.permission, which returns one of three strings:

  • "default": the user has not decided yet. You may ask.
  • "granted": you may show notifications.
  • "denied": you must not. The browser will not ask again until the user changes the site settings by hand.

You request permission with Notification.requestPermission(), which returns a promise for one of those strings:

JavaScript
async function enableReminders() {
  if (!('Notification' in window)) {
    return 'unsupported';
  }
  if (Notification.permission === 'default') {
    return await Notification.requestPermission();
  }
  return Notification.permission;
}

Once permission is "granted", create a notification with the constructor:

JavaScript
const note = new Notification('Break time', {
  body: 'You have been coding for an hour. Stretch for two minutes.',
  icon: '/icons/icon-192.png',
  tag: 'break-reminder',
});

note.addEventListener('click', () => {
  window.focus();
  note.close();
});

tag lets a new notification replace an older one with the same tag instead of piling up. Other options include requireInteraction, silent and data.

Two practical notes:

  • On many Android browsers, new Notification() throws an error. There you must show notifications through a service worker, with registration.showNotification(...), as introduced in Progressive Web Apps.
  • Showing a notification when the site is closed requires the separate Push API together with a service worker and a server. This lesson covers only notifications triggered while your page is open.

Asking permission politely

Browsers increasingly hide or auto-block prompts from pages that ask too soon. The reliable approach has three parts:

  1. Wait for a clear user action. Ask when someone presses "Remind me", never on page load.
  2. Explain the benefit first in your own interface, then trigger the browser prompt.
  3. Respect the answer. If the state is "denied", do not show your own button that cannot work. Explain how to turn it on in browser settings, or offer another channel such as email.

The simulation below follows this flow with a fake permission object, so it works the same everywhere and shows each state. Press the button several times and watch the messages.

The permission flow, simulated

Notice that once the state is denied, pressing "Remind me" never asks again. That is how the real API behaves, and it is why asking at the wrong moment is so costly: you rarely get a second chance.

Putting it together

A common recipe for an article page: a "Share" button that opens the share sheet where available, otherwise a "Copy link" button that uses the Clipboard API, and otherwise a visible text field. Each layer enhances the one below, and nothing depends on a feature the visitor may not have. For the visible-field layer, see Forms.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. A user closes the share sheet without choosing an app. What happens to the promise from navigator.share()?

    Closing the sheet rejects the promise with an AbortError. It means the user changed their mind, so showing an error message would be wrong.
  2. 2. Which is true for navigator.clipboard.writeText() on a real HTTPS page?

    Writing from a user gesture is allowed without a prompt. Reading is the sensitive operation that needs permission or a Paste confirmation.
  3. 3. Notification.permission returns "denied". What should your page do?

    Once denied, the browser will not prompt again. Respect the choice and offer an alternative.
  4. 4. When is the best moment to call Notification.requestPermission()?

    Prompts that follow a clear user action are understood and accepted far more often, and browsers may block prompts that appear unprompted.

Summary

  • Always feature-detect navigator.share, navigator.clipboard and Notification, and design a fallback for each.
  • navigator.share() needs a secure context and a user gesture; an AbortError just means the user cancelled.
  • navigator.clipboard.writeText() copies after a click without a prompt; reading is guarded by permission or a Paste confirmation. The paste event is a simple, permission-free alternative.
  • Notification permission is default, granted or denied; ask only after a clear user action and never keep asking after a denial.
  • On Android and for background messages you need a service worker (and the Push API for closed pages).

Next lesson: Page Visibility, Fullscreen and Screen Wake Lock, where you learn to react when the user leaves the tab and to take over the whole screen.