JavaScript Intermediate Browser APIs · 7 min read

The Clipboard API

Lesson 24 of 38 in the JavaScript learning path.

How do I copy text with navigator.clipboard?

navigator.clipboard.writeText copies a string when the page is a secure context and the call runs inside a user gesture such as a click. The method returns a promise. That promise rejects when permission is denied, when the document is not focused, or when a permissions policy blocks the clipboard.

Copy text the visitor can already see, such as a share link. Do not read the clipboard when the page loads. readText is a separate and more sensitive permission. If writeText rejects, say so in the status and leave the link on screen. The older document.execCommand copy path is obsolete and easy to get wrong.

Syntax & Parameters

Syntax
await navigator.clipboard.writeText(text);

Example

Interactive preview available
app.js
const source = document.createElement("p");
source.id = "share-link";
source.textContent = "https://school.example/lessons/routes";

const copyButton = document.createElement("button");
copyButton.type = "button";
copyButton.id = "copy-link";
copyButton.textContent = "Copy link";

const readButton = document.createElement("button");
readButton.type = "button";
readButton.id = "read-clip";
readButton.textContent = "Read clipboard length";

const status = document.createElement("p");
status.id = "copy-status";
status.textContent = "Ready";

function clipboardReady() {
  return window.isSecureContext === true && typeof navigator.clipboard !== "undefined";
}

async function copyShareLink() {
  const text = (source.textContent || "").trim();
  if (text === "") {
    status.textContent = "Nothing to copy";
    return;
  }
  if (!clipboardReady()) {
    status.textContent = "Clipboard needs a secure page";
    return;
  }
  try {
    await navigator.clipboard.writeText(text);
    status.textContent = "Copied the lesson link";
    copyButton.textContent = "Copied";
  } catch (error) {
    status.textContent = "Copy was blocked";
  }
}

copyButton.addEventListener("click", () => {
  copyShareLink();
});

readButton.addEventListener("click", async () => {
  if (!clipboardReady()) {
    status.textContent = "Clipboard needs a secure page";
    return;
  }
  try {
    const text = await navigator.clipboard.readText();
    status.textContent = "Clipboard holds " + String(text.length) + " characters";
  } catch (error) {
    status.textContent = "Read was denied";
  }
});

document.body.append(source, copyButton, readButton, status);

Expected Output

Ready
https://school.example/lessons/routes

On a secure page, Copy link sets the status to Copied the lesson link.
If the clipboard is blocked, the status is Copy was blocked.
If the page is not a secure context, the status is Clipboard needs a secure page.
Read clipboard length reports a character count, or Read was denied.

Line-by-Line Walkthrough

  1. The paragraph holds the lesson URL as text the visitor can already see.
  2. Both buttons use type button so they do not submit a surrounding form.
  3. clipboardReady requires a secure context and a navigator.clipboard object.
  4. copyShareLink trims the URL and refuses an empty string before it touches the clipboard.
  5. An insecure page gets a status line instead of a thrown error from a missing API.
  6. writeText returns a promise. await waits until the browser accepts or rejects the write.
  7. Success changes the status and the button label to say the link was copied.
  8. A rejection, including a denied permission, is caught and reported as Copy was blocked.
  9. The click listener is the user gesture. Calling writeText while the page loads would reject.
  10. The read button reports only the character count. A denial is caught, and the text is not sent anywhere.

Common Pitfalls & Security

The clipboard is shared with every other application the visitor uses. Treat a write as something they asked for, and treat a read as access to data your page did not create.

  • writeText outside a click or keydown is rejected. Do not call it from a timer or from page load.
  • HTTP on a custom host is not a secure context. localhost is. A non-secure page has no clipboard object.
  • readText can return passwords or other sites' text. Do not upload what you read, and do not read without a deliberate click.
  • A permissions policy can block clipboard-write even on HTTPS. The promise rejects. Catch it.
  • Copying a hidden field the visitor cannot see is a surprise. Copy the link that is on screen.
  • document.execCommand("copy") needs a selection hack and is obsolete. Prefer the Clipboard API.

Best Practices & Modern Standards

Call writeText from the click handler, or from an async function that the click handler starts. Keep the copied string identical to the visible text. Restore the button label after a moment if the control is reused, so the next copy is obvious.

Use readText only for a feature the visitor expects, such as a paste button. Check isSecureContext first and catch every rejection. Offer the visible text as the fallback so a denied permission does not trap the task.

Real-World Use

The share row shows the lesson URL and a Copy link button. The click writes that URL to the clipboard and says it was copied. On an insecure origin, or when the browser denies the permission, the status explains the block and the URL remains visible to copy by hand.

Frequently Asked Questions

Why did writeText reject?

The usual causes are a missing user gesture, a document that is not focused, an insecure page, a denied permission, or a permissions policy that blocks clipboard-write.

Can I copy without a click?

No. The browser requires a user activation for writeText. A timer, a fetch callback, or a load handler is not enough.

What is a secure context?

HTTPS, or a local origin such as localhost. Plain HTTP on a public or custom host is not a secure context, and navigator.clipboard is missing there.

Should I print what readText returns?

Only if the visitor asked to paste that text into your page. This sample reports the length so a clipboard that holds a secret is not echoed into the layout.

Need more coins?

You do not have enough coins for this action.

Your balance: 0 coins

Share

Reactions

Loading reactions…