StackPractices
beginner By Mathias Paulenko

JavaScript Clipboard Copy and Paste

Copy and paste text, HTML, and images in JavaScript with the Clipboard API — secure-context rules, an execCommand fallback, and real browser quirks

Topics: frontend

Overview

Every documentation site and dashboard ends up needing a “Copy” button, and the browser’s Async Clipboard API (navigator.clipboard) is what makes it work without plugins or hidden Flash hacks. The catch: the API only runs in secure contexts, every browser enforces a different permission model, and document.execCommand("copy") — deprecated but still the only option on older engines — needs a selection hack. This recipe covers copying and reading text, pasting rich content with ClipboardItem, intercepting paste events, and the execCommand fallback you still need in 2026.

When to Use

  • You need a “Copy to clipboard” button for code snippets, share URLs, or API tokens
  • You want to read clipboard content, for example a “Paste” button that pre-fills a form
  • You’re building a rich text editor that must sanitize or transform pasted HTML
  • You need clipboard support across modern browsers plus a fallback for older ones

Skip the fallback complexity entirely if your audience is strictly modern browsers behind HTTPS — in that case navigator.clipboard.writeText() alone is enough.

Solution

The snippets are copy-paste ready; a runnable demo page lives in the companion repository.

Basic copy to clipboard

async function copyToClipboard(text) {
    try {
        await navigator.clipboard.writeText(text);
        console.log("Copied to clipboard");
        return true;
    } catch (err) {
        console.error("Failed to copy:", err);
        return false;
    }
}

// Usage
document.getElementById("copy-btn").addEventListener("click", () => {
    copyToClipboard("https://example.com/share-link");
});

Copy with fallback for older browsers

async function copyToClipboard(text) {
    if (navigator.clipboard && window.isSecureContext) {
        try {
            await navigator.clipboard.writeText(text);
            return true;
        } catch (err) {
            // Fall through to fallback
        }
    }

    // Fallback: execCommand
    const textarea = document.createElement("textarea");
    textarea.value = text;
    textarea.style.position = "fixed";
    textarea.style.left = "-9999px";
    document.body.appendChild(textarea);
    textarea.focus();
    textarea.select();

    try {
        const success = document.execCommand("copy");
        document.body.removeChild(textarea);
        return success;
    } catch (err) {
        document.body.removeChild(textarea);
        return false;
    }
}

// Usage
const button = document.querySelector("#copy-btn");
button.addEventListener("click", async () => {
    const ok = await copyToClipboard("text to copy");
    if (ok) {
        button.textContent = "Copied!";
        setTimeout(() => button.textContent = "Copy", 2000);
    }
});

Read text from the clipboard

async function readClipboard() {
    try {
        const text = await navigator.clipboard.readText();
        console.log("Clipboard content:", text);
        return text;
    } catch (err) {
        console.error("Failed to read clipboard:", err);
        return null;
    }
}

// Usage: read clipboard on button click (requires user gesture)
document.getElementById("paste-btn").addEventListener("click", async () => {
    const text = await readClipboard();
    if (text) {
        document.getElementById("output").value = text;
    }
});

In Firefox and Safari, readText() doesn’t throw a permission dialog — it opens an ephemeral “Paste” context menu that the user must click. Chrome requests the clipboard-read permission instead.

Read rich content (HTML, images)

readText() only returns plain text. For HTML or images, use navigator.clipboard.read(), which returns ClipboardItem objects exposing the available MIME types:

async function readRichClipboard() {
    const items = await navigator.clipboard.read();

    for (const item of items) {
        console.log("Available types:", item.types); // e.g. ["text/plain", "text/html", "image/png"]

        if (item.types.includes("text/html")) {
            const blob = await item.getType("text/html");
            const html = await blob.text();
            document.getElementById("editor").innerHTML = sanitizeHtml(html);
        } else if (item.types.includes("image/png")) {
            const blob = await item.getType("image/png");
            const url = URL.createObjectURL(blob);
            document.getElementById("preview").src = url;
        }
    }
}

Always inspect item.types first — the clipboard may hold formats your code can’t handle, and calling getType() on a missing type throws. Sanitize text/html before injecting it (see Sanitize User Input to Prevent XSS); pasted markup from Word or web pages routinely carries scripts and inline styles you don’t want.

Intercept paste events

document.getElementById("editor").addEventListener("paste", (event) => {
    event.preventDefault();

    const clipboardData = event.clipboardData || window.clipboardData;
    const pastedText = clipboardData.getData("text/plain");

    // Sanitize or transform pasted content
    const cleanText = pastedText
        .replace(/<[^>]*>/g, "")
        .replace(/\s+/g, " ")
        .trim();

    document.execCommand("insertText", false, cleanText);
});

// Handle image paste
document.getElementById("image-editor").addEventListener("paste", (event) => {
    const items = event.clipboardData?.items;
    if (!items) return;

    for (const item of items) {
        if (item.type.startsWith("image/")) {
            const file = item.getAsFile();
            const reader = new FileReader();

            reader.onload = (e) => {
                const img = document.createElement("img");
                img.src = e.target.result;
                document.getElementById("preview").appendChild(img);
            };

            reader.readAsDataURL(file);
        }
    }
});

For file inputs that accept both drag-and-drop and paste, the same DataTransferItem API drives both flows — see JavaScript Drag and Drop File Upload.

Copy button for code blocks

function addCopyButtons() {
    const codeBlocks = document.querySelectorAll("pre code");

    codeBlocks.forEach((codeBlock) => {
        const button = document.createElement("button");
        button.className = "copy-btn";
        button.textContent = "Copy";
        button.style.position = "absolute";
        button.style.top = "8px";
        button.style.right = "8px";

        button.addEventListener("click", async () => {
            const text = codeBlock.textContent;
            const ok = await copyToClipboard(text);

            if (ok) {
                button.textContent = "Copied!";
                setTimeout(() => button.textContent = "Copy", 2000);
            }
        });

        const pre = codeBlock.parentElement;
        pre.style.position = "relative";
        pre.appendChild(button);
    });
}

addCopyButtons();

Check clipboard permissions

The Permissions API names clipboard-read and clipboard-write are a Chromium-only feature — Firefox and Safari don’t support them, so query() throws and you should treat that as “attempt the operation anyway”:

async function checkClipboardPermission() {
    try {
        const permission = await navigator.permissions.query({
            name: "clipboard-write"
        });

        if (permission.state === "granted") {
            return true;
        }

        if (permission.state === "prompt") {
            // Will ask on next clipboard operation
            return null;
        }

        return false;
    } catch (err) {
        // Firefox/Safari: permission name not supported, assume available
        return true;
    }
}

// Usage
const canCopy = await checkClipboardPermission();
if (canCopy === false) {
    showNotification("Clipboard access denied. Please enable it in browser settings.");
}

Explanation

The API splits in two surfaces. navigator.clipboard exposes async methods — writeText() and readText() for plain text, write() and read() for arbitrary MIME types wrapped in ClipboardItem. Separately, the cut/copy/paste events fire on focusable elements and give you event.clipboardData to inspect or override the operation. A newer clipboardchange event on the Clipboard object notifies when the system clipboard contents change — useful for apps that sync their own internal clipboard.

Copy decision flow: a user gesture triggers a check for secure context and navigator.clipboard; if available it calls writeText, otherwise it falls back to a hidden textarea with execCommand, then shows feedback

Three constraints decide whether a call works:

  • Secure context: navigator.clipboard exists only on HTTPS or localhost. On plain HTTP the property is undefined, so window.isSecureContext is the guard you want before falling back — which is also why production needs TLS (see Setup SSL Certificates).
  • Transient user activation: writes must be triggered by a user action in every engine. Chrome additionally persists the clipboard-write permission once granted, so later calls don’t need a gesture.
  • Permission model divergence: this is where most “works in Chrome, fails elsewhere” bugs come from. Chromium prompts for clipboard-read on the first read. Firefox and Safari don’t implement the clipboard-read/clipboard-write permission names at all — instead, a read inside a user gesture opens an ephemeral “Paste” context menu (enabled after ~1 second) and only succeeds if the user clicks it.

Two more edge cases worth knowing:

  • Iframes: a framed page can’t touch the clipboard unless the embedder grants it — the iframe needs allow="clipboard-read; clipboard-write" (and the matching Permissions-Policy header). Without it, calls reject with NotAllowedError.
  • Failed promises: every clipboard method returns a promise that rejects with a DOMException — NotAllowedError for permission/gesture problems, SecurityError for context violations. An unhandled rejection is a silent failure: the button does nothing and the user copies by hand.

The fallback document.execCommand("copy") is deprecated but still covers legacy WebViews and pre-2020 engines. It needs a real selectable element — the off-screen textarea trick — and it only works synchronously inside the same user gesture that triggered it.

Variants

MethodBrowser SupportAsyncUse When
navigator.clipboard.writeTextModern browsersYesDefault choice, HTTPS only
document.execCommand("copy")All browsersNoFallback for legacy engines
navigator.clipboard.readTextModern browsersYesPlain-text paste (prompts differ per engine)
navigator.clipboard.read / writeChrome, Edge, SafariYesHTML, images, custom MIME types
paste event handlerAll browsersNoSanitizing or transforming pasted input

Best Practices

  • Always try navigator.clipboard first and keep execCommand as fallback, guarded by window.isSecureContext.
  • Give visual feedback after copy — swap the label to “Copied!” or flip an icon for ~2 seconds. Without it users click twice and blame the button.
  • Handle the rejected promise every time; a denied permission should surface a message, not silence.
  • Sanitize pasted HTML before it reaches the DOM — raw markup from other apps is an XSS vector.
  • Read the clipboard only inside a user gesture. In Firefox and Safari the read literally becomes a second click on a “Paste” prompt, so design your UX around that extra step.
  • Test on a real phone: iOS Safari and Android WebViews have their own quirks for execCommand and focus.

Common Mistakes

  • Calling navigator.clipboard on HTTP — the property doesn’t exist outside secure contexts, so feature-check window.isSecureContext first.
  • Not handling the rejected promise — the most common cause of “copy button does nothing” is a denied permission or a missing user gesture.
  • Forgetting to remove the off-screen textarea in the fallback — every failed copy leaks a DOM node.
  • Assuming readText() prompts like Chrome’s — in Firefox and Safari the user sees a “Paste” menu instead of a permission dialog, and it silently waits for their click.
  • Framing your app without allow="clipboard-*" — clipboard calls inside the iframe reject even though the same code works top-level.
  • Injecting clipboardData.getData("text/html") straight into innerHTML — you get whatever scripts and inline styles the source app copied.

Troubleshooting

  • Copy works on localhost but fails on a LAN IP (192.168.x.x): the LAN origin isn’t a secure context. Test with HTTPS, a tunnel (ngrok, cloudflared), or keep the fallback for that environment.
  • Button copies once, then stops working in Chrome: check for an unhandled rejection from a previous call — inspect chrome://settings/content/clipboard to see whether clipboard-write ended up denied.
  • readText() hangs in Firefox or Safari: expected — the browser is showing the ephemeral “Paste” menu and the promise stays pending until the user clicks it.
  • read() returns an item but getType() throws: the clipboard holds formats you didn’t check for. Always read item.types first; images copied from some apps arrive as image/png while others only offer text/html with an inline <img>.
  • Permission query throws: clipboard-read/clipboard-write aren’t supported by navigator.permissions outside Chromium. Treat a thrown query() as “unknown” and attempt the operation inside a user gesture.

Further Reading

Frequently Asked Questions

Why does navigator.clipboard not work on localhost with HTTP?

The Clipboard API requires a secure context. localhost is treated as secure even over HTTP, but other HTTP origins aren't — that's why it breaks on LAN IPs and staging servers. Use HTTPS in production or test on localhost.

How do I copy rich text or HTML to the clipboard?

Use navigator.clipboard.write() with a ClipboardItem:

const htmlBlob = new Blob(["<b>Bold text</b>"], { type: "text/html" });
const textBlob = new Blob(["Bold text"], { type: "text/plain" });

await navigator.clipboard.write([
    new ClipboardItem({
        "text/html": htmlBlob,
        "text/plain": textBlob
    })
]);

Always include a text/plain fallback so apps that can't render HTML still get something.

Can I copy without a button click?

Not reliably. Every engine requires transient user activation for writes, and Chrome only skips the gesture when the clipboard-write permission was already granted. Copying on page load or inside a setTimeout without a prior interaction will reject.

Why does clipboard access fail inside an iframe?

The iframe needs explicit delegation: allow="clipboard-read; clipboard-write" on the tag, plus a Permissions-Policy header if the embedder restricts it. Without delegation the calls reject with NotAllowedError even though they work top-level.

How do I copy an image to the clipboard?

Use navigator.clipboard.write() with a PNG blob:

const response = await fetch("image.png");
const blob = await response.blob();

await navigator.clipboard.write([
    new ClipboardItem({ "image/png": blob })
]);

Safari only accepts image/png for image writes; Chrome supports more types.