clipboard-polyfill vs react-clipboard.js vs react-copy-to-clipboard
Clipboard Interaction Libraries
clipboard-polyfillreact-clipboard.jsreact-copy-to-clipboardSimilar Packages:

Clipboard Interaction Libraries

Clipboard interaction libraries in JavaScript provide developers with tools to programmatically access and manipulate the clipboard, allowing for actions like copying and pasting text or images. These libraries abstract the complexities of the Clipboard API, offering simple interfaces for tasks such as copying content to the clipboard, handling paste events, and managing clipboard data across different browsers. They are particularly useful in web applications that require enhanced clipboard functionality, such as text editors, sharing tools, or any app that needs to interact with the user's clipboard seamlessly. clipboard-polyfill is a lightweight library that provides a consistent API for clipboard operations across browsers, including those that do not fully support the modern Clipboard API. react-clipboard.js is a React component that simplifies copying text to the clipboard with minimal setup, leveraging the Clipboard API and providing built-in support for handling copy events. react-copy-to-clipboard is a flexible React component that allows developers to wrap any element and enable copying its content to the clipboard with a simple API, including support for customizable copy actions and event handling.

Npm Package Weekly Downloads Trend

3 Years

Github Stars Ranking

Stat Detail

Package
Downloads
Stars
Size
Issues
Publish
License
clipboard-polyfill0928404 kB9a year agoMIT
react-clipboard.js0271-106 years agoCC0
react-copy-to-clipboard02,37440.6 kB25-MIT

Feature Comparison: clipboard-polyfill vs react-clipboard.js vs react-copy-to-clipboard

Cross-Browser Compatibility

  • clipboard-polyfill:

    clipboard-polyfill provides robust cross-browser compatibility, including support for older browsers and those with incomplete Clipboard API implementations. It ensures consistent behavior across different environments, making it reliable for applications that need to function on a wide range of devices and browsers.

  • react-clipboard.js:

    react-clipboard.js relies on the modern Clipboard API for its functionality, which is supported in most modern browsers. However, it may not handle older browsers or those with limited support as gracefully as clipboard-polyfill, making it more suitable for applications targeting contemporary web environments.

  • react-copy-to-clipboard:

    react-copy-to-clipboard is designed to work with the modern Clipboard API, providing good compatibility across current browsers. It does not specifically address older browsers, so developers should be aware of this limitation when using it in applications that require backward compatibility.

Ease of Use

  • clipboard-polyfill:

    clipboard-polyfill offers a straightforward API for clipboard operations, but it requires some understanding of how to integrate it into your application. It is more of a utility library than a plug-and-play solution, which may require additional setup for optimal use.

  • react-clipboard.js:

    react-clipboard.js provides an easy-to-use interface for copying text in React applications. Its component-based design allows for quick integration, and it handles the complexities of clipboard interactions, making it user-friendly for developers.

  • react-copy-to-clipboard:

    react-copy-to-clipboard is highly intuitive and easy to use, especially for React developers. Its simple API allows for quick implementation of copy functionality, and its flexibility in wrapping elements makes it versatile for various use cases.

Customization

  • clipboard-polyfill:

    clipboard-polyfill is not highly customizable, as it focuses on providing a consistent API for clipboard operations. However, its simplicity allows developers to use it in a variety of contexts without needing extensive configuration.

  • react-clipboard.js:

    react-clipboard.js offers limited customization, primarily around the text being copied and the handling of copy events. It is designed to be simple and straightforward, which may limit its flexibility for more complex use cases.

  • react-copy-to-clipboard:

    react-copy-to-clipboard excels in customization, allowing developers to specify the text to be copied, handle copy events, and even customize the appearance and behavior of the component. This makes it a great choice for applications that require more control over the copy functionality.

Code Example

  • clipboard-polyfill:

    Clipboard Polyfill Example

    import { writeText } from 'clipboard-polyfill/text';
    
    async function copyToClipboard(text) {
      try {
        await writeText(text);
        console.log('Text copied to clipboard!');
      } catch (err) {
        console.error('Failed to copy text: ', err);
      }
    }
    
    copyToClipboard('Hello, World!');
    
  • react-clipboard.js:

    React Clipboard.js Example

    import React from 'react';
    import { CopyToClipboard } from 'react-clipboard.js';
    
    function ClipboardComponent() {
      return (
        <CopyToClipboard text="Hello, World!">
          <button>Copy to Clipboard</button>
        </CopyToClipboard>
      );
    }
    
    export default ClipboardComponent;
    
  • react-copy-to-clipboard:

    React Copy to Clipboard Example

    import React, { useState } from 'react';
    import { CopyToClipboard } from 'react-copy-to-clipboard';
    
    function CopyExample() {
      const [text, setText] = useState('Hello, World!');
      const [copied, setCopied] = useState(false);
    
      return (
        <div>
          <input
            type="text"
            value={text}
            onChange={(e) => setText(e.target.value)}
          />
          <CopyToClipboard
            text={text}
            onCopy={() => setCopied(true)}
          >
            <button>Copy</button>
          </CopyToClipboard>
          {copied && <span>Copied!</span>}
        </div>
      );
    }
    
    export default CopyExample;
    

How to Choose: clipboard-polyfill vs react-clipboard.js vs react-copy-to-clipboard

  • clipboard-polyfill:

    Choose clipboard-polyfill if you need a lightweight, cross-browser solution that provides a consistent API for clipboard operations, especially in environments with limited support for the modern Clipboard API.

  • react-clipboard.js:

    Choose react-clipboard.js if you are building a React application and want a simple, component-based approach to copying text to the clipboard, with built-in support for copy events and minimal configuration.

  • react-copy-to-clipboard:

    Choose react-copy-to-clipboard if you need a highly customizable and flexible solution for copying content in a React app, with support for wrapping any element and handling copy actions programmatically.

README for clipboard-polyfill

Logo for clipboard-polyfill: an icon of a clipboard fading into a drafting paper grid.

clipboard-polyfill

⚠️ You don't need clipboard-polyfill to copy text! ⚠️

Note: As of 2020, you can use navigator.clipboard.writeText(...) in the stable versions of all major browsers. This library will only be useful to you if you want to:

  • target very old browsers (see below for compatibility) for text copy,
  • copy text/html in Firefox ≤126,
  • use the ClipboardItem API in Firefox ≤126, or
  • polyfill the API shape in a non-browser environment (e.g. in jsdom).

See the Compatibility section below for more details.


Summary

Makes copying on the web as easy as:

clipboard.writeText("hello world");

This library is a ponyfill/polyfill for the modern Promise-based asynchronous clipboard API.

Usage

If you use npm, install:

npm install clipboard-polyfill

Sample app that copies text to the clipboard:

import * as clipboard from "clipboard-polyfill";

function handler() {
  clipboard.writeText("This text is plain.").then(
    () => { console.log("success!"); },
    () => { console.log("error!"); }
  );
}

window.addEventListener("DOMContentLoaded", function () {
  const button = document.body.appendChild(document.createElement("button"));
  button.textContent = "Copy";
  button.addEventListener("click", handler);
});

Notes:

  • You need to call a clipboard operation in response to a user gesture (e.g. the event handler for a button click).
    • Some browsers may only allow one clipboard operation per gesture.

async/await syntax

import * as clipboard from "clipboard-polyfill";

async function handler() {
  console.log("Previous clipboard text:", await clipboard.readText());

  await clipboard.writeText("This text is plain.");
}

window.addEventListener("DOMContentLoaded", function () {
  const button = document.body.appendChild(document.createElement("button"));
  button.textContent = "Copy";
  button.addEventListener("click", handler);
});

More MIME types (data types)

import * as clipboard from "clipboard-polyfill";

async function handler() {
  console.log("Previous clipboard contents:", await clipboard.read());

  const item = new clipboard.ClipboardItem({
    "text/html": new Blob(
      ["<i>Markup</i> <b>text</b>. Paste me into a rich text editor."],
      { type: "text/html" }
    ),
    "text/plain": new Blob(
      ["Fallback markup text. Paste me into a rich text editor."],
      { type: "text/plain" }
    ),
  });
  await clipboard.write([item]);
}

window.addEventListener("DOMContentLoaded", function () {
  const button = document.body.appendChild(document.createElement("button"));
  button.textContent = "Copy";
  button.addEventListener("click", handler);
});

Check the Clipboard API specification for more details.

Notes:

  • You'll need to use async functions for the await syntax.
  • Currently, text/plain and text/html are the only data types that can be written to the clipboard across most browsers.
  • If you try to copy unsupported data types, they may be silently dropped (e.g. Safari 13.1) or the call may throw an error (e.g. Chrome 83). In general, it is not possible to tell when data types are dropped.
  • In some current browsers, read() may only return a subset of supported data types, even if the clipboard contains more data types. There is no way to tell if there were more data types.

overwrite-globals version

If you want the library to overwrite the global clipboard API with its implementations, import clipboard-polyfill/overwrite-globals. This will turn the library from a ponyfill into a proper polyfill, so you can write code as if the async clipboard API were already implemented in your browser:

import "clipboard-polyfill/overwrite-globals";

async function handler() {
  const item = new window.ClipboardItem({
    "text/html": new Blob(
      ["<i>Markup</i> <b>text</b>. Paste me into a rich text editor."],
      { type: "text/html" }
    ),
    "text/plain": new Blob(
      ["Fallback markup text. Paste me into a rich text editor."],
      { type: "text/plain" }
    ),
  });

  navigator.clipboard.write([item]);
}

window.addEventListener("DOMContentLoaded", function () {
  const button = document.body.appendChild(document.createElement("button"));
  button.textContent = "Copy";
  button.addEventListener("click", handler);
});

This approach is not recommended, because it may break any other code that interacts with the clipboard API globals, and may be incompatible with future browser implementations.

Flat-file version with Promise included

If you need to grab a version that "just works", download clipboard-polyfill.window-var.promise.es5.js and include it using a <script> tag:

<script src="./clipboard-polyfill.window-var.promise.es5.js"></script>
<button onclick="copy()">Copy text!</button>
<script>
  // `clipboard` is defined on the global `window` object.
  function copy() {
    clipboard.writeText("hello world!");
  }
</script>

Bundling / tree shaking / minification / CommonJS

Thanks to the conveniences of the modern JS ecosystem, we do not provide tree shaken, minified, or CommonJS builds anymore. To get such builds without losing compatibility, pass clipboard-polyfill builds through esbuild. For example:

mkdir temp && cd temp && npm install clipboard-polyfill esbuild

# Minify the ES6 build:
echo 'export * from "clipboard-polyfill";' | npx esbuild --format=esm --target=es6 --bundle --minify

# Include just the `writeText()` export and minify:
echo 'export { writeText } from "clipboard-polyfill";' | npx esbuild --format=esm --target=es6 --bundle --minify

# Minify an ES5 build:
cat node_modules/clipboard-polyfill/dist/es5/window-var/clipboard-polyfill.window-var.promise.es5.js | npx esbuild --format=esm --target=es5 --bundle --minify

# Get a CommonJS build:
echo 'export * from "clipboard-polyfill";' | npx esbuild --format=cjs --target=es6 --bundle

Why clipboard-polyfill?

Browsers have implemented several clipboard APIs over time, and writing to the clipboard without triggering bugs in various old and current browsers is fairly tricky. In every browser that supports copying to the clipboard in some way, clipboard-polyfill attempts to act as close as possible to the async clipboard API. (See above for disclaimers and limitations.)

See this presentation for for a longer history of clipboard access on the web.

Compatibility

  • ☑️: Browser has native async clipboard support.
  • ✅: clipboard-polyfill adds support.
  • ❌: Support is not possible.
  • Bold browser names indicate the latest functionality changes for stable versions of modern browsers.

Write support by earliest browser version:

BrowserwriteText()write() (HTML)write() (other formats)
Safari 13.1☑️☑️☑️ (image/uri-list, image/png)
Chrome 86ᵃ / Edge 86☑️☑️☑️ (image/png)
Chrome 76ᵃ / Edge 79☑️☑️ (image/png)
Chrome 66ᵃ / Firefox 63☑️
Safari 10 / Chrome 42ᵃ / Edgeᵈ / Firefox 41✅ᵇ
IE 9✅ᶜ

Read support:

BrowserreadText()read() (HTML)read() (other formats)
Safari 13.1☑️☑️☑️ (image/uri-list, image/png)
Chrome 76 ᵃ / Edge 79☑️☑️ (image/png)
Chrome 66☑️
IE 9✅ᶜ
Firefox
  • ᵃ Also includes versions of Edge, Opera, Brave, Vivaldi, etc. based on the corresponding version of Chrome.
  • ᵇ HTML did not work properly on mobile Safari in the first few releases of version 10.
  • ᶜ In Internet Explorer, you will need to polyfill window.Promise if you want the library to work.
  • ᵈ In older versions of Edge (Spartan):
    • It may not be possible to tell if a copy operation succeeded (Edge Bug #14110451, Edge Bug #14080262). clipboard-polyfill will always report success in this case.
    • Only the last data type you specify is copied to the clipboard (Edge Bug #14080506). Consider placing the most important data type last in the object that you pass to the ClipboardItem constructor.
    • The text/html data type is not written using the expected CF_HTML format. clipboard-polyfill does not try to work around this, since 1) it would require fragile browser version sniffing, 2) users of Edge are not generally stuck on version < 17, and 3) the failure mode for other browsers would be that invalid clipboard HTML is copied. (Edge Bug #14372529, #73)

clipboard-polyfill uses a variety of heuristics to work around compatibility bugs. Please let us know if you are running into compatibility issues with any of the browsers listed above.

History

Browser history

BrowserFirst version supporting
navigator.clipboard.writeText(...)
Release Date
Chrome66+April 2018
Firefox53+October 2018
Edge79+ (first Chromium-based release)January 2020
Safari13.1+March 2020

Project history

This project dates from a time when clipboard access in JS was barely becoming possible, and ergonomic clipboard API efforts were stalling. (See this presentation for a bit more context.) Fortunately, an ergonomic API with the same functionality is now available in all modern browsers since 2020:

Thanks to Gary Kacmarcik, Hallvord Steen, and others for helping to bring the async clipboard API to life!

This is way too complicated!

If you only need to copy text in modern browsers, consider using navigator.clipboard.writeText() directly: https://caniuse.com/mdn-api_clipboard_writetext

If you need copy text in older browsers as well, you could also try this gist for a simple hacky solution.