Comprehensive Clipboard API Guide & Examples

Note: Many examples require HTTPS (or localhost) and a user gesture (like a click). Reading clipboard data often requires user permission. The monitor on the right updates best via its Refresh button or after copy/cut actions *on this page*. Check your browser's console (F12) for errors.


Introduction to Clipboard Functionality

Web developers can implement copy and paste functionality using browser APIs to interact with the system clipboard. The clipboard is a temporary data buffer used for short-term data storage and transfer between applications.

Modern web development primarily utilizes the Async Clipboard API, which offers significant advantages (like asynchronous operations, better security, and richer data type support) over the older, now deprecated document.execCommand() method.


The Modern Async Clipboard API

The Async Clipboard API provides a way to asynchronously read from and write to the system clipboard, preventing the browser from freezing when handling large amounts of data. It is accessed through the global navigator.clipboard object.

Key Interfaces

Writing Data to the Clipboard

Writing Plain Text

The simplest way to copy text is using navigator.clipboard.writeText(text). It takes a string and returns a Promise that resolves when the text is successfully copied or rejects if it fails (e.g., due to lack of permission or not being triggered by a user gesture).

Example: `clipboard.writeText()`

Writing Multiple Data Formats (Rich Text, Images)

For more complex data like HTML or images, or to provide multiple formats simultaneously (like HTML with a plain text fallback), use navigator.clipboard.write(items).

This method takes an array containing one or more ClipboardItem objects. Each ClipboardItem is created with an object where keys are MIME types (strings) and values are the data in that format, typically as a Blob or a Promise that resolves to a Blob or string.

The order of MIME types within a ClipboardItem can matter, as some applications might prioritize the first type they understand. It's common practice to put the richest format (like text/html) first, followed by fallbacks (like text/plain).

Example: `clipboard.write()` (Rich Text)

Edit the content below, then copy it.

This is bold and italic text.

  • With a list item!

Example: `clipboard.write()` (Copying Image Tag)

This copies an HTML <img> tag as text/html, with the image URL as a text/plain fallback.

Test Image from fakeimg.pl

Note: To copy the actual image data (not just the tag), you would fetch the image, create an image/* Blob, and use that in the ClipboardItem.

Reading Data from the Clipboard

Reading requires user permission, which the browser typically prompts for on the first attempt per origin. Reading must often occur shortly after a user gesture (like clicking a "Paste" button) or when the document has focus.

Reading Plain Text

Use navigator.clipboard.readText() to get the clipboard content as plain text. It returns a Promise that resolves with the text string or rejects on failure (permission denied, no text content, etc.).

Example: `clipboard.readText()`

Reading Multiple Data Formats

Use navigator.clipboard.read() to access all available data formats. It returns a Promise that resolves to an array of ClipboardItem objects currently on the clipboard.

You then iterate through the items and, for each item, check its item.types array (a list of MIME type strings). You can request the data for a specific type using item.getType(mimeType), which returns a Promise resolving to a Blob. You can then process the Blob (e.g., read it as text using blob.text() or display it as an image using URL.createObjectURL(blob)).

Example: `clipboard.read()` (General Content)

Copy different types of content (text, rich text, images from a graphics editor) outside the browser, then click below to try reading it.

(Output will appear here)


Security Considerations

The Async Clipboard API has several built-in security measures:

iframe Example (`srcdoc` and `allow`)

This example demonstrates an iframe embedded using the srcdoc attribute. The parent document grants clipboard access via allow="clipboard-read; clipboard-write". The JavaScript *inside* the iframe can then attempt to use the Clipboard API.

Example: `iframe` with `srcdoc` and Permissions

Note: The monitor on the right won't automatically update from iframe actions unless complex cross-frame communication (like postMessage) is implemented.


The Deprecated `document.execCommand()` Method

Warning: The document.execCommand('copy') and document.execCommand('paste') methods are deprecated. They have limitations, inconsistent browser support, and synchronous behavior that can block the main thread. The Async Clipboard API should always be preferred. These examples are shown for historical context or potential fallback scenarios only.

execCommand('copy') typically only works reliably when text within an editable element (like <input> or <textarea>) is selected. A common workaround for non-editable content involved creating a temporary, off-screen textarea, putting the text in it, selecting the text, executing the command, and then removing the temporary element.

Example: `execCommand('copy')` (Editable Field)

Example: `execCommand('copy')` (Workaround)

Copy this non-editable text using the legacy workaround.


Clipboard Events (`copy`, `cut`, `paste`)

Browsers fire copy, cut, and paste events when the user initiates these actions through the browser's native UI (e.g., keyboard shortcuts Ctrl+C/Cmd+C, Ctrl+X/Cmd+X, Ctrl+V/Cmd+V, or the right-click context menu).

You can listen for these events on specific elements or the document. The event handler receives a ClipboardEvent object, which has a clipboardData property (a DataTransfer object).

These events are useful for intercepting native clipboard actions, perhaps to sanitize pasted content or to provide custom data formats during a copy/cut operation initiated by the user.

Example: Handling Clipboard Events

Try copying, cutting, or pasting text within the blue dashed box using keyboard shortcuts (Ctrl+C/X/V) or the context menu. Check the status below and the console log.

Try copying text from here or pasting text into here... The 'copy' event here adds a prefix. The 'paste' event prevents default insertion and logs the data.

(Event status will appear here)


Progressive Enhancement

Given that browser support for specific Clipboard API features (especially read() and writing complex types) can vary, and older browsers might not support the API at all, it's wise to use progressive enhancement.

This means your application's core functionality should ideally work without relying on advanced clipboard features. You can then detect support for the Async Clipboard API and enhance the user experience where available. If the modern API isn't supported, you might (cautiously) fall back to the deprecated document.execCommand method, clearly understanding its limitations.

Example: Progressive Enhancement for Copying Text

This button attempts to use navigator.clipboard.writeText() first. If that fails or isn't available, it falls back to the legacy document.execCommand('copy') workaround.


Summary

The modern Async Clipboard API (navigator.clipboard) is the standard and recommended way to handle copy and paste operations in web applications. It offers asynchronous operations, improved security, and support for multiple data types via ClipboardItem objects. Key considerations include handling permissions, ensuring actions occur within user gestures, being aware of secure context requirements, and using progressive enhancement for broader compatibility. While deprecated methods exist, they should be avoided in favor of the modern API.

Clipboard Monitor

Click Refresh or copy/cut on page to update.

API Feature Support
Checking...