Skip to main content

Overview

The copyToClipboard function provides a modern way to copy content to the clipboard using the Clipboard API, with automatic fallback to legacy methods for broader browser support.

Import

import { copyToClipboard } from "@zayne-labs/toolkit-core";

Signature

function copyToClipboard(
  valueToCopy: AllowedClipboardItems | Promise<AllowedClipboardItems>,
  options?: CopyToClipboardOptions
): Promise<void>

Parameters

valueToCopy
string | Blob | Promise<string | Blob>
required
The content to copy to the clipboard. Can be a string, Blob, or a Promise that resolves to either.
options
CopyToClipboardOptions
Optional configuration object.
options.mimeType
string
The MIME type of the content. Defaults to "text/plain".Common values:
  • "text/plain" (default)
  • "text/html"
  • "image/png"
options.onSuccess
() => void
Callback function called when the copy operation succeeds.
options.onError
(error: unknown) => void
Callback function called when the copy operation fails.
options.onCopied
() => void
Callback function called after copy completes (whether via Clipboard API or fallback).

Return Value

Promise<void>
Promise
A promise that resolves when the copy operation completes. Errors are caught internally and passed to onError.

Usage Examples

Basic Text Copy

const copyText = async () => {
  await copyToClipboard("Hello, clipboard!");
  console.log("Text copied!");
};

With Success Callback

const copyWithFeedback = async (text: string) => {
  await copyToClipboard(text, {
    onSuccess: () => {
      console.log("Successfully copied to clipboard!");
    },
    onError: (error) => {
      console.error("Failed to copy:", error);
    }
  });
};

Copy HTML Content

const copyHTML = async () => {
  const htmlContent = "<strong>Bold text</strong>";
  
  await copyToClipboard(htmlContent, {
    mimeType: "text/html",
    onCopied: () => {
      console.log("HTML copied!");
    }
  });
};

Copy Image Blob

const copyImage = async (imageUrl: string) => {
  const response = await fetch(imageUrl);
  const blob = await response.blob();
  
  await copyToClipboard(blob, {
    mimeType: "image/png",
    onSuccess: () => console.log("Image copied to clipboard"),
    onError: (error) => console.error("Failed to copy image:", error)
  });
};

Copy with Async Content

const copyAsyncContent = async () => {
  // Pass a Promise directly
  await copyToClipboard(
    fetch("/api/data").then(res => res.text()),
    {
      onSuccess: () => console.log("Async content copied!")
    }
  );
};

React Integration Example

import { copyToClipboard } from "@zayne-labs/toolkit-core";
import { useState } from "react";

function CopyButton({ text }: { text: string }) {
  const [copied, setCopied] = useState(false);

  const handleCopy = async () => {
    await copyToClipboard(text, {
      onSuccess: () => {
        setCopied(true);
        setTimeout(() => setCopied(false), 2000);
      },
      onError: (error) => {
        console.error("Copy failed:", error);
      }
    });
  };

  return (
    <button onClick={handleCopy}>
      {copied ? "Copied!" : "Copy to Clipboard"}
    </button>
  );
}

Types

CopyToClipboardOptions

type CopyToClipboardOptions = {
  mimeType?: "text/plain" | string;
  onCopied?: () => void;
  onError?: (error: unknown) => void;
  onSuccess?: () => void;
};

AllowedClipboardItems

type AllowedClipboardItems = string | Blob;

Behavior

  1. Primary Method: Uses the modern Clipboard API (navigator.clipboard.write)
  2. MIME Type Check: Validates that the specified MIME type is supported
  3. Fallback: For text content, automatically falls back to document.execCommand('copy') if the Clipboard API fails
  4. Error Handling: All errors are caught and logged, with optional onError callback

Browser Support

  • Modern Browsers: Full support via Clipboard API
  • Legacy Browsers: Automatic fallback for text content
  • HTTPS Required: Clipboard API requires secure context (HTTPS or localhost)

Common Use Cases

  • Copy code snippets from documentation
  • Copy share links or URLs
  • Copy formatted text or HTML
  • Copy generated content (tokens, IDs, etc.)
  • Copy images or other media

Notes

  • The Clipboard API requires a secure context (HTTPS or localhost)
  • Some MIME types may not be supported in all browsers
  • The fallback method only works for string content
  • For better UX, always provide user feedback via callbacks
  • The onCopied callback fires regardless of whether the primary or fallback method was used

Build docs developers (and LLMs) love