copy-to-clipboard vs clipboard-copy vs clipboard-polyfill
Clipboard Interaction Libraries
copy-to-clipboardclipboard-copyclipboard-polyfillSimilar Packages:

Clipboard Interaction Libraries

Clipboard interaction libraries provide developers with tools to easily copy text to the clipboard, enhancing user experience by allowing seamless data transfer without the need for manual selection and copying. These libraries abstract the complexities of clipboard APIs and offer straightforward methods for copying text, ensuring compatibility across different browsers and environments. They are particularly useful in web applications where users frequently need to copy information, such as links, text snippets, or formatted data, thus improving usability and efficiency.

Npm Package Weekly Downloads Trend

3 Years

Github Stars Ranking

Stat Detail

Package
Downloads
Stars
Size
Issues
Publish
License
copy-to-clipboard9,626,6041,39733.5 kB1111 days agoMIT
clipboard-copy801,329634-75 years agoMIT
clipboard-polyfill146,803927404 kB9a year agoMIT

Feature Comparison: copy-to-clipboard vs clipboard-copy vs clipboard-polyfill

Browser Compatibility

  • copy-to-clipboard:

    copy-to-clipboard is compatible with most modern browsers and provides a fallback mechanism for older ones. It is a reliable choice for developers looking for a balance between functionality and compatibility.

  • clipboard-copy:

    clipboard-copy is designed to work seamlessly in modern browsers, leveraging the Clipboard API where available. It does not support older browsers, which may limit its use in applications requiring extensive compatibility.

  • clipboard-polyfill:

    clipboard-polyfill provides a comprehensive solution for clipboard interactions by offering a fallback for browsers that do not support the Clipboard API. This makes it ideal for applications that need to support a wider range of users, including those on older browsers.

Ease of Use

  • copy-to-clipboard:

    copy-to-clipboard has a user-friendly API that is easy to implement, making it accessible for developers of all skill levels. Its straightforward approach allows for quick integration into projects.

  • clipboard-copy:

    clipboard-copy offers a very simple API that allows developers to copy text with just one function call. This ease of use makes it an attractive option for developers looking for quick implementation without extensive setup.

  • clipboard-polyfill:

    clipboard-polyfill requires a bit more configuration due to its polyfill nature, but it provides detailed documentation to help developers navigate its use. It may not be as straightforward as clipboard-copy but is still manageable for those familiar with JavaScript.

Functionality

  • copy-to-clipboard:

    copy-to-clipboard allows for copying not just plain text but also HTML and other formats, making it a versatile choice for applications that need to handle various data types.

  • clipboard-copy:

    clipboard-copy focuses solely on copying text to the clipboard, providing a clean and efficient solution for this specific task. It does not handle complex data types or formats, which may limit its use in more advanced scenarios.

  • clipboard-polyfill:

    clipboard-polyfill supports a broader range of clipboard operations, including copying text and handling different data types. This versatility makes it suitable for applications that require more complex clipboard interactions.

Community Support

  • copy-to-clipboard:

    copy-to-clipboard boasts a larger user base and community support, which translates to a wealth of resources, tutorials, and examples available online, making it easier for developers to find help.

  • clipboard-copy:

    clipboard-copy has a smaller community compared to some other libraries, which may result in fewer resources and examples available for troubleshooting or advanced use cases.

  • clipboard-polyfill:

    clipboard-polyfill has a dedicated community and is actively maintained, providing good documentation and support for developers. This can be beneficial for those needing assistance or looking for best practices.

Performance

  • copy-to-clipboard:

    copy-to-clipboard is also optimized for performance, providing a quick and efficient way to copy text to the clipboard without significant delays, making it suitable for high-frequency operations.

  • clipboard-copy:

    clipboard-copy is optimized for performance, focusing on a lightweight implementation that minimizes overhead. It is suitable for applications where speed and efficiency are critical.

  • clipboard-polyfill:

    clipboard-polyfill may introduce some overhead due to its polyfill nature, but it is designed to handle clipboard operations efficiently across various environments, ensuring a good balance between performance and compatibility.

How to Choose: copy-to-clipboard vs clipboard-copy vs clipboard-polyfill

  • copy-to-clipboard:

    Opt for copy-to-clipboard if you want a widely used library with a straightforward API and good community support. It is versatile and can handle various data types, making it suitable for applications that require more than just plain text copying.

  • clipboard-copy:

    Choose clipboard-copy for a simple and modern API that focuses on copying text to the clipboard with minimal configuration. It is lightweight and works well in most modern browsers, making it ideal for straightforward use cases.

  • clipboard-polyfill:

    Select clipboard-polyfill if you need a more robust solution that ensures compatibility across older browsers. This package provides a polyfill for the Clipboard API, allowing you to handle clipboard interactions gracefully in environments where native support may be lacking.

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.formatString. 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 droppedwindow.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.