copy-to-clipboard
Copy text to the clipboard from the browser with automatic fallbacks for older or non-secure contexts.
Repository Health
Technical Analysis
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 returningPromise<boolean> - Automatic Async Clipboard API usage in secure contexts, with
execCommandfallback elsewhere - Support for copying non-plain-text formats (e.g.
text/html) via theformatoption - An
onCopyhook to intercept and replace theClipboardItemorDataTransferpayload 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/htmlandtext/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.
Used by 28 apps in this directory
Plasmic
CMS · Design Tools · Low Code Platforms
The open-source visual builder that lets teams design React apps and websites with drag-and-drop while integrating seamlessly with your codebase.
Postiz
Automation · Social Media
The agentic social media scheduler — AI-powered content creation, 33-platform posting, and team workflows, all self-hosted.
QRev
AI Agents · CRM
Open source AI-first sales platform that replaces Salesforce with autonomous agents handling prospecting, outreach, and lead management at scale.
Refly
AI Development · Automation · No Code Platforms
Build deterministic, versioned agent skills from natural language—run them anywhere from Claude Code to Slack.
Tabby
AI Code Assistants
Self-hosted AI coding assistant — run GitHub Copilot-grade code completion on your own hardware with no cloud dependency.
Teable
Databases · No Code Platforms
A no-code PostgreSQL database with spreadsheet UX, real-time collaboration, and native AI agents — built for teams that outgrow Airtable.
Tianji
Analytics · Monitoring
Replace Google Analytics, UptimeKuma, and Prometheus with one self-hosted platform that tracks websites, monitors uptime, and reports server health.
Tolgee
Developer Tools
In-context localization platform that lets developers and translators edit app strings directly in the running application, with AI-powered machine translation and framework SDKs for React, Angular, Vue, and Svelte.
Unleash
Ab Testing Experimentation · Developer Tools · Devops
The open-source feature management platform that lets you ship code to production and control who sees it — without redeploying.