Frontend Development 9 min read

Understanding Clipboard Operations: clipboard.js and the Async Clipboard API

This article explains the system‑level nature of the clipboard, analyzes how clipboard.js implements copy via a hidden textarea and execCommand, discusses its limitations, and introduces the modern Async Clipboard API with its Promise‑based read/write methods, usage notes, and browser support.

360 Tech Engineering
360 Tech Engineering
360 Tech Engineering
Understanding Clipboard Operations: clipboard.js and the Async Clipboard API

Clipboard Overview

The clipboard is a short‑term data buffer provided by the operating system for cut, copy, and paste operations, making it a system‑level feature.

clipboard.js Principle

clipboard.js (https://clipboardjs.com/) uses two existing Web APIs: HTMLInputElement.select() and document.execCommand() . Its implementation consists of two steps:

Create a hidden temporary textarea element, assign the text to copy, and select its content.

Trigger the copy command; if successful, the text is written to the clipboard and a custom event is dispatched.

Key code excerpt:

// https://github.com/zenorocha/clipboard.js/blob/master/src/clipboard-action.js
/**
 * Creates a fake textarea element, sets its value from `text` property,
 * and makes a selection on it.
 */
// selectFake()
// 创建临时的texterea元素
this.fakeElem = document.createElement('textarea');
// 隐藏这个元素
this.fakeElem.style.position = 'absolute';
this.fakeElem.style[ isRTL ? 'right' : 'left' ] = '-9999px';
// 把要复制的文本赋给文本区并选择全部内容
this.fakeElem.value = this.text;
this.selectedText = select(this.fakeElem);
// 触发复制
this.copyText();
/**
 * Executes the copy operation based on the current selection.
 */
// copyText()
succeeded = document.execCommand(this.action);
this.handleResult(succeeded);
/**
 * Fires an event based on the copy operation result.
 * @param {Boolean} succeeded
 */
handleResult(succeeded) {
  this.emitter.emit(succeeded ? 'success' : 'error', {
    action: this.action,
    text: this.selectedText,
    trigger: this.trigger,
    clearSelection: this.clearSelection.bind(this)
  });
}

While widely supported, clipboard.js suffers from several drawbacks: reliance on execCommand (originally for editing DOM), synchronous execution that blocks the main thread, inconsistent browser implementations, and limited data type handling.

Existing Technique Drawbacks

execCommand was designed for DOM editing and varies across browsers.

Copy/paste operations are synchronous and can block the UI.

Additional permission prompts may annoy users.

Handling of certain data types (e.g., images) is restricted.

To address these issues, the W3C defined the Clipboard API and events, introducing an asynchronous, Promise‑based Clipboard API.

Async Clipboard API

The new API is exposed on navigator.clipboard and provides four methods:

Promise<DataTransfer> read();
Promise<DOMString> readText();
Promise<void> write(DataTransfer data);
Promise<void> writeText(DOMString data);

Supported data types include plain text, various MIME types, images, and binary streams.

read()

navigator.clipboard.read().then(function(data) {
  for (var i = 0; i < data.items.length; i++) {
    if (data.items[i].type == "text/plain") {
      console.log("Your string: ", data.items[i].getAs("text/plain"));
    } else {
      console.error("No text/plain data on clipboard.");
    }
  }
});

readText()

navigator.clipboard.readText().then(function(data) {
   console.log("Your string: ", data);
});

write(data)

var data = new DataTransfer();
data.items.add("text/plain", "Howdy, partner!");
navigator.clipboard.write(data).then(function() {
  console.log("Copied to clipboard successfully!");
}, function() {
  console.error("Unable to write to clipboard. :-(");
});

writeText(data)

navigator.clipboard.writeText("Howdy, partner!").then(function() {
  console.log("Copied to clipboard successfully!");
}, function() {
  console.error("Unable to write to clipboard. :-(");
});

Important Considerations

navigator.clipboard works only in secure contexts (HTTPS or localhost). Use window.isSecureContext to check.

Desktop support currently includes Chrome, Firefox, and Opera; Safari and Edge lack full support, and Chrome only implements readText() and writeText() .

References

https://clipboardjs.com/

https://www.w3.org/TR/clipboard-apis/

https://developers.google.com/web/updates/2018/03/clipboardapi

https://w3c.github.io/webappsec-secure-contexts

frontendJavaScriptWeb APIClipboardclipboard.jsAsync Clipboard API
360 Tech Engineering
Written by

360 Tech Engineering

Official tech channel of 360, building the most professional technology aggregation platform for the brand.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.