copy-to-clipboard vs react-copy-to-clipboard vs clipboard-copy vs vue-clipboard2 vs ngclipboard
Choosing text-copy functions or AngularJS, React and Vue integration
copy-to-clipboardreact-copy-to-clipboardclipboard-copyvue-clipboard2ngclipboardSimilar Packages:

Choosing text-copy functions or AngularJS, React and Vue integration

clipboard-copy is a Promise-based text helper, copy-to-clipboard has an async boolean result and configurable paths, and the other entries attach clipboard behavior to specific frameworks. ngclipboard targets AngularJS, not a generic current Angular application.

Npm Package Weekly Downloads Trend

3 Years

Github Stars Ranking

Stat Detail

Package
Downloads
Stars
Size
Issues
Publish
License
copy-to-clipboard15,019,2761,39733.5 kB167 months agoMIT
react-copy-to-clipboard2,672,8082,36737.9 kB158 months agoMIT
clipboard-copy714,520632-86 years agoMIT
vue-clipboard2128,8171,749-375 years agoMIT
ngclipboard22,43938219.4 kB23-MIT

Start from the actual framework

ngclipboard is an AngularJS directive over Clipboard.js. Its published peer is the AngularJS angular package, so its name should not be interpreted as a current Angular component integration. It can be useful for an existing AngularJS application without being a general recommendation for every Angular project.

React Copy to Clipboard and Vue Clipboard2 likewise expose their own framework arrangements. A framework-free function can instead be called by an application-owned event handler if that gives a clearer lifecycle.

Two different Promise outcomes

clipboard-copy provides a focused text-copy operation. Its Promise resolves on success and rejects when copying fails. The application can connect those outcomes to interface feedback.

The current copy-to-clipboard returns Promise<boolean>. Awaiting it is necessary, but the resolved boolean must also be inspected. Its configured asynchronous and DOM fallback paths are not the same contract as a helper whose rejection alone represents failure.

Neither API should be called speculatively outside the browser's supported clipboard environment or required interaction. Keep those prerequisites in the application's event flow rather than expecting the wrapper to create them.

Directive and component lifecycle

Ngclipboard attaches an AngularJS directive to a trigger and exposes its success/error callback arrangement. Use the expected module registration and element attributes. Its direct user value is maintaining that specific framework integration; its package download count alone is not a reason to introduce AngularJS into another application.

React Copy to Clipboard wraps one child and calls onCopy(text, result) from its click handler. Its declared copy-to-clipboard dependency targets a synchronous-returning distribution, unlike the independently published latest copy function. Preserve the wrapper callback contract instead of inferring it from another package's current README.

Vue Clipboard2 provides a programmatic Promise helper and directives over Clipboard.js. Its implementation selects a prototype or global-properties branch for the helper, while the directives still use bind/update/unbind-style lifecycle hooks. Verify the actual helper and directive path for the Vue host separately; one branch is not proof of complete Vue integration.

Keep feedback connected to completion

Choose a focused helper for application-owned copying or a wrapper that matches the actual framework. Map the real completion result to the UI, including an awaited false result where applicable. Similar callback names do not make those return and lifecycle contracts interchangeable.

How to Choose: copy-to-clipboard vs react-copy-to-clipboard vs clipboard-copy vs vue-clipboard2 vs ngclipboard

  • copy-to-clipboard:

    Use its current Promise contract and options when the additional copy paths or MIME handling are useful. Await and inspect the result rather than assuming rejection is the only failure signal.

  • react-copy-to-clipboard:

    Use its single-child click integration and callback when that matches the React component. Its bound synchronous dependency and callback result differ from the independently published async copy function.

  • clipboard-copy:

    Use a focused text-copy function whose Promise resolves on success and rejects on failure. Keep the call in the required user interaction and handle rejection explicitly.

  • vue-clipboard2:

    Choose its programmatic helper or directive deliberately and check the selected Vue host path. Do not infer full directive compatibility from the helper's global-properties branch.

  • ngclipboard:

    Use its directive in an existing AngularJS application with the declared angular peer. It is not an Angular component or directive for an unrelated modern Angular host.

README for copy-to-clipboard

Copy to clipboard CI

Simple module exposing an async copy function that uses the Async Clipboard API (navigator.clipboard) in secure contexts (HTTPS / localhost), with automatic fallback to document.execCommand('copy') for non-secure contexts or older browsers.

If you are building using Electron, use their API.

Example

import copy from 'copy-to-clipboard';

await copy('Text');

// Copy with options
await copy('Text', {
  debug: true,
  message: 'Press #{key} to copy',
});

// Copy as HTML (text/html + text/plain written simultaneously)
await copy('<b>Hello <i>world</i></b>', { format: 'text/html' });

// Custom plain-text fallback via onCopy
await copy('<b>Hello <i>world</i></b>', {
  format: 'text/html',
  onCopy: () => new ClipboardItem({
    'text/html': new Blob(['<b>Hello <i>world</i></b>'], { type: 'text/html' }),
    'text/plain': new Blob(['Hello world'], { type: 'text/plain' }),
  }),
});

API

copy(text: string, options?: object): Promise<boolean> — copies text to clipboard. Returns true on success, false if all paths failed (no additional keystrokes were required from the user).

v4 breaking change: copy() is now async and returns Promise<boolean>. Use await copy(...) to get the result.

Options

ValueDefaultNotes
options.debugfalseBoolean. Enable output to console.
options.message'Copy to clipboard: #{key}, Enter'String. Prompt message used when fallbackToPrompt is enabled. All occurrences of #{key} are replaced with ⌘+C on macOS or Ctrl+C otherwise.
options.format—String. MIME type to copy as. Use 'text/html' to copy rich text; 'text/plain' to strip inherited styles when pasting into rich-text editors. When set alongside 'text/html', both text/html and text/plain are written simultaneously via ClipboardItem.
options.onCopy—(clipboardData: ClipboardItem | DataTransfer) => ClipboardItem | void. Called before the write. On the async path, receives the constructed ClipboardItem and may return a new one to replace it (useful for custom MIME types or a different plain-text fallback). On the execCommand fallback path, receives the DataTransfer object; return value is ignored.
options.fallbackToPromptfalseBoolean. If true, shows a window.prompt() as a last resort when both navigator.clipboard and execCommand fail. Off by default in v4.

Copy path selection

  1. navigator.clipboard.writeText(text) — used when the page is a secure context (HTTPS / localhost), navigator.clipboard is available, and neither options.format nor options.onCopy is set.
  2. navigator.clipboard.write([ClipboardItem]) — used in a secure context when options.format or options.onCopy is set. Builds a ClipboardItem with text/plain always present; adds the requested MIME type alongside it. onCopy may return a replacement ClipboardItem.
  3. execCommand('copy') fallback — used on non-HTTPS pages, when navigator.clipboard is unavailable, or when the async write throws. Uses a hidden <span> element. preventDefault is only called when options.format is set.
  4. window.prompt() fallback — opt-in via options.fallbackToPrompt: true.

Recipes

HTML copy with stripped plain-text fallback

By default, copy(html, { format: 'text/html' }) puts the raw HTML string in the text/plain slot of the ClipboardItem. If you want apps that only accept plain text to receive readable content instead of markup, use onCopy to supply a stripped version:

function stripHtml(html) {
  const div = document.createElement('div');
  div.innerHTML = html;
  return div.textContent || div.innerText || '';
}

const html = '<b>Hello <i>world</i></b>';

await copy(html, {
  format: 'text/html',
  onCopy: () => new ClipboardItem({
    'text/html': new Blob([html], { type: 'text/html' }),
    'text/plain': new Blob([stripHtml(html)], { type: 'text/plain' }),
  }),
});
// text/html  → '<b>Hello <i>world</i></b>'
// text/plain → 'Hello world'

Custom MIME type

await copy('col1,col2\nval1,val2', {
  format: 'text/csv',
});
// text/csv   → 'col1,col2\nval1,val2'
// text/plain → 'col1,col2\nval1,val2'  (always included as fallback)

Browser support

BrowserMinimumNotes
Chrome76+Full ClipboardItem + write() support
Firefox127+Full ClipboardItem + write() landed in Firefox 127 (mid-2024)
Safari13.1+writeText() and write() available
Edge79+Chromium-based; same as Chrome

execCommand fallback retains support for non-HTTPS contexts and any browser that reaches the catch path.

Note: The async clipboard write must occur within a user gesture (click, keydown, etc.). This library is designed to be called from event handlers, so this constraint is normally satisfied automatically.

Installation

npm i copy-to-clipboard

Available as CommonJS, ES module, and IIFE (for <script> tags):

// ESM
import copy from 'copy-to-clipboard';

// CommonJS
const copy = require('copy-to-clipboard');
<!-- IIFE via CDN — exposes window.copyToClipboard -->
<script src="https://unpkg.com/copy-to-clipboard/dist/index.global.js"></script>

TypeScript

Built-in declarations are included for both CommonJS and ESM consumers.

import copy from 'copy-to-clipboard';
import type { Options } from 'copy-to-clipboard';

const result: boolean = await copy('text');

UI components based on this package

See also

Running Tests

End-to-end tests are powered by Nightwatch using native browser drivers.

npm i
npm test               # Chrome (default)
npm run test:firefox
npm run test:safari
npm run test:edge
npm run test:all       # all local browsers

Safari prerequisite: enable "Allow Remote Automation" in Safari's Develop menu. See Testing with WebDriver in Safari.

CI

Chrome, Firefox, and Edge tests run automatically on every push to master and on pull requests via GitHub Actions (Ubuntu runner, headless).

Cross-browser tests (Chrome, Firefox, Safari, Edge) run on LambdaTest automatically on every version tag (v*) and can be triggered manually from the Actions tab. Requires LT_USERNAME and LT_ACCESS_KEY repository secrets.

npm run test:lt:chrome
npm run test:lt:firefox
npm run test:lt:safari
npm run test:lt:edge
npm run test:lt:all

Breaking changes in v4

  1. copy() is now async — returns Promise<boolean> instead of boolean. Wrap call sites with await.
  2. IE11 support dropped — window.clipboardData path removed.
  3. window.prompt() fallback is opt-in — set options.fallbackToPrompt: true to enable.
  4. Build output moved to dist/ — direct require('copy-to-clipboard/index.js') paths will break; use the package name only.