or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

index.md
tile.json

tessl/npm-copy-to-clipboard

Copy stuff into clipboard using JS with fallbacks

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
npmpkg:npm/copy-to-clipboard@3.3.x

To install, run

npx @tessl/cli install tessl/npm-copy-to-clipboard@3.3.0

index.mddocs/

Copy to Clipboard

Copy to Clipboard is a JavaScript library that provides cross-browser clipboard functionality with intelligent fallback mechanisms. It attempts to copy text to the clipboard using modern browser APIs, with graceful degradation for older browsers and a user prompt fallback as the last resort.

Package Information

  • Package Name: copy-to-clipboard
  • Package Type: npm
  • Language: JavaScript (with TypeScript definitions)
  • Installation: npm install copy-to-clipboard

Core Imports

import copy from 'copy-to-clipboard';

For CommonJS:

const copy = require('copy-to-clipboard');

For TypeScript:

import copy from 'copy-to-clipboard';
// or
import * as copy from 'copy-to-clipboard';

For browsers via CDN:

<script src="https://wzrd.in/standalone/copy-to-clipboard@latest"></script>
<!-- Available as window.copyToClipboard -->

Basic Usage

import copy from 'copy-to-clipboard';

// Simple copy
const success = copy('Hello, world!');
if (success) {
  console.log('Text copied successfully');
} else {
  console.log('Copy required user interaction');
}

// Copy with options
const success = copy('Text to copy', {
  debug: true,
  message: 'Press #{key} to copy',
  format: 'text/plain',
  onCopy: (clipboardData) => {
    console.log('Copy event triggered');
  }
});

Architecture

Copy to Clipboard implements a three-tier fallback strategy:

  1. Primary: Modern browsers using document.execCommand('copy')
  2. Secondary: IE11/Edge using window.clipboardData.setData()
  3. Tertiary: User prompt with copy instructions as last resort

The library creates a temporary DOM element, selects its content, executes the copy command, and cleans up afterward while preserving the user's original text selection.

Capabilities

Copy Function

The main function that copies text to the clipboard with intelligent fallbacks.

/**
 * Copies text to clipboard with fallback mechanisms
 * @param text - The text content to copy to clipboard
 * @param options - Optional configuration object
 * @returns boolean - true if copy succeeded without user interaction, false if user interaction was required
 */
function copy(text: string, options?: Options): boolean;

interface Options {
  /** Enable console debugging output. Default: false */
  debug?: boolean;
  /** Custom prompt message for fallback. #{key} gets replaced with Ctrl+C or ⌘+C. Default: "Copy to clipboard: #{key}, Enter" */
  message?: string;
  /** MIME type for clipboard data (e.g., 'text/plain', 'text/html'). Default: undefined */
  format?: string;
  /** Callback function receiving clipboardData object for custom behavior */
  onCopy?: (clipboardData: object) => void;
}

Parameters:

  • text (string, required): The text content to copy to clipboard
  • options (object, optional): Configuration options
    • debug (boolean): Enable debugging console output. Shows detailed information about fallback attempts.
    • message (string): Custom message template for the user prompt fallback. The placeholder #{key} is replaced with ⌘+C on macOS/iOS or Ctrl+C on other platforms.
    • format (string): MIME type for clipboard content. Use 'text/html' for HTML content or 'text/plain' to avoid style inheritance when pasting into rich text editors.
    • onCopy (function): Callback executed during the copy event, receiving the clipboardData object for advanced manipulation like setting multiple formats.

Returns:

  • boolean: Returns true if the copy operation succeeded without requiring user interaction (using execCommand or clipboardData APIs). Returns false if the operation fell back to a user prompt, indicating the user needed to manually copy the text.

Usage Examples:

import copy from 'copy-to-clipboard';

// Basic text copy
copy('Simple text');

// Copy with debugging enabled
copy('Debug text', { debug: true });

// Copy HTML content
copy('<strong>Bold text</strong>', { 
  format: 'text/html' 
});

// Copy with custom fallback message
copy('Custom message text', {
  message: 'Please use #{key} to copy this text'
});

// Copy with callback for multiple formats
copy('Multi-format text', {
  onCopy: (clipboardData) => {
    clipboardData.setData('text/plain', 'Plain text version');
    clipboardData.setData('text/html', '<em>HTML version</em>');
  }
});

// Handle return value
const success = copy('Important data');
if (!success) {
  // User interaction was required - the text was shown in a prompt
  alert('Please copy the text from the prompt dialog');
}

Browser Support

  • Full Support: Chrome, Firefox, Safari 10+, Internet Explorer 11, Edge
  • Partial Support: Safari 8 (prompt fallback only, cannot pre-fill prompt content)
  • Limited Support: Some older iOS devices may not work properly
  • Fallback Support: Any browser with prompt() support

The library automatically detects browser capabilities and uses the best available method:

  1. Modern browsers use document.execCommand('copy') for seamless copying
  2. IE11/Edge uses window.clipboardData.setData() when execCommand fails
  3. All other cases fall back to window.prompt() with copy instructions

Error Handling

The function handles errors gracefully by falling through the three-tier system:

  • execCommand failures: Automatically tries IE-specific clipboardData
  • clipboardData failures: Falls back to user prompt
  • Complete failures: Returns false and shows prompt as last resort

When debug: true is enabled, detailed error information is logged to the console showing which methods were attempted and why they failed.

Related Packages

Based on copy-to-clipboard:

  • react-copy-to-clipboard - React wrapper component
  • copy-button - Standalone copy button implementation

Alternative: