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
Apache Answer
Community
Open-source Q&A platform for communities, help centers, and knowledge bases with AI assistant and plugin extensibility
Appsmith
Developer Tools · Automation · No Code Platforms
Open-source low-code platform to build admin panels, dashboards, and internal tools connected to any database or API.
Blinko
Knowledge Management · Note Taking
A self-hosted, AI-powered card note-taking tool that lets you capture fleeting thoughts instantly and retrieve them with natural language search.
Databasement
Databases · Devops · Developer Tools
Self-hosted database backup manager with a web UI for scheduling, encrypting, and restoring MySQL, PostgreSQL, MongoDB, SQL Server, SQLite, Firebird, and Redis to S3, SFTP, Samba, or local storage.
Dify
No Code Platforms · AI Development · Developer Tools
Visual LLM workflow platform with RAG pipelines, agent capabilities, and model management for building production AI applications.
Dokploy
Devops · Hosting Control Panel · Security
Self-hosted PaaS that deploys apps and databases on your own VPS using Docker, Traefik, and multi-build-system orchestration
ILLA Builder
Developer Tools · Low Code Platforms · No Code Platforms
Open-source low-code platform for building internal tools with drag-and-drop UI, reactive data bindings, and real-time collaboration.
Kibana
Analytics · Monitoring
Your open source window into the Elastic Stack — query, visualize, and act on data stored in Elasticsearch with real-time dashboards, AI-assisted search, and automated alerting.
LibreChat
Developer Tools · AI Assistants
Unite every major AI model in one self-hosted chat platform with agents, code execution, MCP tools, and enterprise authentication.