TechEarl

Copy and Paste with the Clipboard API (navigator.clipboard)

Copy and paste in JavaScript with navigator.clipboard: writeText/readText, write/read with ClipboardItem for images and HTML, the secure-context requirement, the user-gesture rule, and the clipboard-read vs clipboard-write permissions.

Ishan KarunaratnePublished ⏱️ 8 min readUpdated
Share thisCopied
Copy and paste in JavaScript with the asynchronous Clipboard API: writeText, readText, ClipboardItem for images and HTML, the HTTPS secure-context rule, and clipboard read/write permissions.

To copy text to the clipboard in JavaScript, call navigator.clipboard.writeText(). To read it back, call navigator.clipboard.readText(). Both are asynchronous and return a promise, both require a secure context (HTTPS or localhost), and the call should originate from a user gesture like a click (Firefox and Safari require that; Chromium also accepts a granted permission). That is the whole job for plain text:

javascript
async function teCopy(text) {
  await navigator.clipboard.writeText(text);
}

async function tePaste() {
  return navigator.clipboard.readText();
}

Wire teCopy to a button's click handler and you have a working "copy to clipboard" feature. The rest of this page is the detail behind those four lines: the gotchas that make it fail silently, copying images and rich HTML with ClipboardItem, the permission model, and what to do about the old document.execCommand('copy') you may have inherited.

This is the modern replacement for the bad old days of clipboard hacks. If you remember Flash-based ZeroClipboard or wrapping clipboard.js around a hidden textarea, you can throw all of it out. The asynchronous Clipboard API is native, promise-based, and supported across every current browser.

Copy and paste text

writeText and readText are the two you reach for ninety percent of the time. Both are async, so you await them (or chain .then):

javascript
const copyBtn = document.querySelector("#copy");

copyBtn.addEventListener("click", async () => {
  try {
    await navigator.clipboard.writeText("https://techearl.com");
    copyBtn.textContent = "Copied";
  } catch (err) {
    console.error("Copy failed:", err);
  }
});

Reading is the mirror image. Pasting is more privacy-sensitive than copying, because a page reading your clipboard could scrape whatever you last copied (a password, a card number), so browsers gate readText harder than writeText:

javascript
pasteBtn.addEventListener("click", async () => {
  const text = await navigator.clipboard.readText();
  document.querySelector("#out").value = text;
});

The async bug to avoid

The single most common mistake is writing the handler as an arrow function with await inside but no async on it:

javascript
// Broken: `await` is a syntax error here, no `async` on the callback.
copyBtn.addEventListener("click", (e) => {
  await navigator.clipboard.writeText("text");
});

That does not even parse. Mark the callback async (as in the working example above), or use .then(). It is an easy slip because the surrounding code often is not in an async function, and the editor does not always flag it until runtime.

You need a secure context (HTTPS or localhost)

navigator.clipboard is undefined on plain HTTP. Per the W3C spec the API is exposed only in a secure context, which in practice means HTTPS, or http://localhost during development. This trips people up constantly: the copy button works perfectly on localhost, ships to a staging box served over bare HTTP, and navigator.clipboard is suddenly missing, so the handler throws Cannot read properties of undefined. Guard for it rather than assuming the object exists:

javascript
if (!navigator.clipboard) {
  // No secure context (or a very old browser). Fall back or disable the button.
  console.warn("Clipboard API unavailable; serve over HTTPS or localhost.");
}

It must run from a user gesture

Even on HTTPS, treat a user gesture as required: call writeText/readText inside the handler for a real user action such as a click or a keydown. The exact rule depends on the browser and on whether you are writing or reading, which is why "it works in Chrome" is not proof that it works everywhere:

  • Writing in Firefox and Safari requires transient activation, the short window right after a user interaction. A write on page load or long after the click is rejected.
  • Writing in Chromium requires either transient activation or the clipboard-write permission. Once that permission is granted it persists, and later writes do not need a fresh gesture.
  • Reading in Chromium triggers a clipboard-read permission request when the document has focus, and succeeds once the user has granted it.
  • Reading in Firefox and Safari needs transient activation and then shows a small "Paste" prompt the user has to click, except when the clipboard content came from the same origin.

All of this is by design: a page should not be able to silently rewrite or read your clipboard in the background. The portable pattern is to keep the actual writeText/readText call in the gesture's own handler, not await slow work first (the activation window can expire), and wrap the call in try/catch so a rejection is handled instead of assumed away.

Permissions: clipboard-read vs clipboard-write

The two operations map to two different permission names, and mixing them up is a real bug I have seen in the wild:

  • clipboard-write governs writing. In Chromium a write succeeds with either this permission or transient activation, so writeText from a click handler usually just works with no prompt.
  • clipboard-read governs reading. This is the gated one. Chromium prompts the user the first time a page calls readText/read, and Firefox and Safari gate reading differently: there is no permission to grant, the user gets a "Paste" confirmation prompt instead.

If you query the Permissions API before reading, query clipboard-read, not clipboard-write. They are not interchangeable:

javascript
// Correct: querying read permission before a paste.
const status = await navigator.permissions.query({ name: "clipboard-read" });
if (status.state === "granted" || status.state === "prompt") {
  const text = await navigator.clipboard.readText();
}

Note that clipboard-read and clipboard-write are Chromium-only as Permissions API names. Firefox and Safari do not support them and do not plan to, so treat a failed permissions.query as "just try the operation and catch the rejection" rather than a hard blocker.

Copy images and HTML with ClipboardItem

For anything that is not plain text (a PNG, rich HTML, both at once), use navigator.clipboard.write() with one or more ClipboardItem objects. Each ClipboardItem maps MIME types to Blobs, so you can put several representations of the same thing on the clipboard at once:

javascript
async function teCopyImage(blob) {
  const item = new ClipboardItem({ [blob.type]: blob });
  await navigator.clipboard.write([item]);
}

// Copy as both HTML and plain text so it pastes well anywhere.
async function teCopyRich(html, text) {
  await navigator.clipboard.write([
    new ClipboardItem({
      "text/html": new Blob([html], { type: "text/html" }),
      "text/plain": new Blob([text], { type: "text/plain" }),
    }),
  ]);
}

Browsers commonly support text/plain, text/html, and image/png here. PNG is the safe image type; many engines reject other image formats from write() as a security measure.

Detect what is on the clipboard

read() gives you back an array of ClipboardItems, and each one exposes a types array so you can branch on what is actually there before pulling the blob:

javascript
async function tePasteSmart() {
  const items = await navigator.clipboard.read();
  for (const item of items) {
    if (item.types.includes("image/png")) {
      const blob = await item.getType("image/png");
      return { kind: "image", blob };
    }
    if (item.types.includes("text/plain")) {
      const blob = await item.getType("text/plain");
      return { kind: "text", text: await blob.text() };
    }
  }
}

This is the right way to handle a paste that might be a screenshot or might be text: check types, then getType() the one you want.

The deprecated fallback: document.execCommand('copy')

Before the async API there was document.execCommand('copy'), which copied the current DOM selection. It is deprecated and should not be reached for in new code, but you will still see it as a fallback for ancient browsers or non-secure contexts:

javascript
// Legacy fallback only. Synchronous, selection-based, deprecated.
function teCopyLegacy(text) {
  const ta = document.createElement("textarea");
  ta.value = text;
  document.body.appendChild(ta);
  ta.select();
  document.execCommand("copy");
  ta.remove();
}

In 2026 you almost never need this. Every current browser supports navigator.clipboard.writeText, so the only realistic reason to keep execCommand around is supporting a page that genuinely cannot be served over HTTPS, and the better fix there is to fix the transport.

See also

Almost always because the page is not in a secure context. The Clipboard API is exposed only over HTTPS or on http://localhost. On plain HTTP, navigator.clipboard is undefined and the copy handler throws. Serve the page over HTTPS (or test on localhost) and check if (!navigator.clipboard) before using it.

Two usual causes. First, the call did not come from a user gesture. Firefox and Safari only allow a write during transient activation (right after a click or key press), and Chromium needs either that or a granted clipboard-write permission, so call writeText inside a real click or keydown handler, not on page load. Second, the handler used await without being marked async, which is a syntax error. Mark the callback async and wrap the call in try/catch to surface the rejection.

clipboard-write governs copying; in Chromium a write works with either that permission or a user gesture. clipboard-read governs pasting and is the gated one: Chromium prompts before a page reads the clipboard. Firefox and Safari do not implement either permission and show a "Paste" prompt for reads instead. If you query the Permissions API before a paste, query clipboard-read, not clipboard-write.

Use navigator.clipboard.write() with a ClipboardItem that maps the MIME type to a Blob, for example new ClipboardItem({ "image/png": blob }). PNG is the broadly supported image type; many browsers reject other image formats from write() for security reasons.

No, not in new code. It is deprecated. Use navigator.clipboard.writeText(), which every current browser supports. Keep execCommand only as a fallback for a page that genuinely cannot be served over HTTPS, and the better fix is to fix the transport.

Sources

Authoritative references this article was fact-checked against.

Tagsclipboard apinavigator.clipboardcopy to clipboard javascriptwriteTextreadTextClipboardItemJavaScript

Found this useful? Pass it on.

Copied

Ishan Karunaratne

Systems and Network Architect · Chief Technology Officer

Systems and network architect and Chief Technology Officer with more than two decades designing, building, and running production software, cloud and network architecture, Linux systems, and the bare metal underneath them, and lately working AI into the stack. A US Army veteran who served in Operation Iraqi Freedom. What I write here is drawn from the full arc of that work, across architecture, engineering, and operations, not any single job.

Keep reading

Related posts

AWS S3 CLI cheat sheet: aws s3 cp local-to-S3, S3-to-local, S3-to-S3 cross-region; aws s3 sync incremental with --delete; --exclude and --include patterns; --storage-class STANDARD_IA / INTELLIGENT_TIERING / GLACIER; --sse AES256 and --sse aws:kms; --acl bucket-owner-full-control; --dryrun for safety; concurrency tuning with max_concurrent_requests and multipart_chunksize; the trailing-slash gotcha that ruins half of all aws s3 cp invocations.

AWS S3 cp and sync Cheat Sheet: Copy, Move, and Sync Files with the CLI

A scannable AWS S3 CLI reference: aws s3 cp, sync, mv, rm, ls; recursive uploads and downloads; --exclude / --include filters; storage classes (STANDARD_IA, GLACIER, INTELLIGENT_TIERING); SSE encryption (AES256, aws:kms); --dryrun safety; the trailing-slash gotcha; concurrency tuning via max_concurrent_requests and multipart_chunksize; cross-account profiles.

Build RAG with embeddings, chunking, vector search and reranking, plus semantic search in MySQL 9 with the VECTOR type. When long context replaces RAG.

How to Build RAG with Embeddings and Vector Search

Build RAG with embeddings, chunking, and vector search. Covers OpenAI / Voyage / Cohere embeddings, chunk sizes, semantic search in MySQL 9 with the VECTOR type, hybrid search, reranking, and when long context replaces RAG entirely.