copy-to-clipboard

Copy text to the clipboard from the browser with automatic fallbacks for older or non-secure contexts.

Library
npm
v4.0.2
1,397 stars
MIT License

Repository Health

Pre-computed score based on development activity, maintenance, community, maturity, and trend momentum. How we score it →
48 /100 Fair
Development Activity 20
Maintenance 20
Community 52
Maturity 60
Momentum 40

Technical Analysis

AI-assessed by reading the actual repository — architecture, code quality, innovation, and documentation. How we score it →
80 /100 Excellent
Architecture 78
Code Quality 75
Innovation 82
Learning Curve 85

copy-to-clipboard is a small JavaScript module that copies text to the clipboard from the browser. It uses the modern Async Clipboard API (navigator.clipboard) when running in a secure context, and automatically falls back to document.execCommand('copy') for non-secure pages or older browsers, with an opt-in window.prompt() fallback as a last resort. Version 4 made the exported copy() function async, returning a Promise<boolean> that resolves to whether the copy succeeded.

The library ships as CommonJS, ESM, and an IIFE build for direct <script> tag usage, with bundled TypeScript declarations for both module formats. It supports copying rich content via a format option (e.g. text/html) and an onCopy hook for intercepting or replacing the clipboard payload before it’s written, making it useful beyond plain-text copy buttons.

What You Get

  • A single default-exported copy(text, options?) function returning Promise<boolean>
  • Automatic Async Clipboard API usage in secure contexts, with execCommand fallback elsewhere
  • Support for copying non-plain-text formats (e.g. text/html) via the format option
  • An onCopy hook to intercept and replace the ClipboardItem or DataTransfer payload before writing
  • CJS, ESM, and IIFE (CDN <script> tag) builds with bundled TypeScript declarations
  • An opt-in window.prompt() fallback (fallbackToPrompt) for environments where both clipboard paths fail

Common Use Cases

  • Adding a “copy” button next to a code snippet, API key, or share link in a web app
  • Copying rich HTML content (e.g. from a WYSIWYG editor) to the clipboard as both text/html and text/plain
  • Building UI copy affordances that need to work correctly on both HTTPS and non-secure/legacy pages
  • Copying custom MIME-typed data (like CSV) for pasting into spreadsheet or rich-text applications

Under The Hood

Architecture — index.ts implements a single tiered copy(text, options) async function. When window.isSecureContext and navigator.clipboard are available it tries copyViaClipboardAPI, which calls navigator.clipboard.writeText() for the plain-text case or builds a ClipboardItem (via buildClipboardItem) and calls navigator.clipboard.write() when a custom format or onCopy hook is supplied. On failure or unavailability it falls through to copyViaExecCommand, which creates a visually-hidden, screen-reader-hidden <span> (createHiddenSpan), selects its contents with the Selection/Range APIs, and triggers document.execCommand('copy'); a findOpenedModalDialog helper walks up from document.activeElement to append the span inside an open <dialog> (or the fullscreen element) so the copy works when the page is in a modal or fullscreen state. A toggle-selection dependency (deselectCurrent) saves and restores the user’s prior text selection around the operation. If both paths fail, an opt-in window.prompt() fallback is offered as a last resort.

Tech Stack — Written in TypeScript (index.ts), compiled to CommonJS, ESM, and an IIFE global build via tsup, with publint used to validate package.json export correctness. The only runtime dependency is toggle-selection; there are no framework dependencies. declarations.d.ts and generated .d.ts/.d.mts files ship types for both module systems.

Code Quality — There are no jsdom-style unit tests; instead the tests/ directory holds seven Nightwatch end-to-end specs (sanity check, basic/multiline/markup/rich text, dialog copy, fullscreen, tabbed text) that drive real Chrome/Firefox/Safari/Edge instances via native webdrivers — an appropriate strategy given the code’s entire surface area is browser Clipboard/Selection API interaction that jsdom cannot faithfully emulate. Each copy path is wrapped in try/catch with debug-gated console logging, and copyViaExecCommand uses a finally block to guarantee selection and DOM cleanup (removing the hidden span, restoring the previous selection) even when the copy fails. Function and variable naming is consistent and descriptive of the exact copy path taken.

API Design — The public surface is a single default export, copy(text: string, options?: Options): Promise<boolean>, requiring zero configuration for the common case (await copy('text')). The Options type is documented inline with JSDoc and covers debug, message (prompt text), format (MIME type), onCopy (payload interception), and fallbackToPrompt. The README documents a clear v4 breaking-change migration note (sync → async), install instructions for all three module formats, and worked recipes for HTML-copy-with-plain-text-fallback and custom MIME types, keeping the getting-started path to a single await call.

Join founders buildingwith open source

Opinionated takes, migration guides, cost-saving tips, and insights from the open source ecosystem.

Subscribe on Substack
Join 750+ subscribers