How to interact with the clipboard using JavaScript

neotam Avatar

Clipboard - Copy, Cut and Paste Using JavaScript

Tags :

It’s never been a easier job to copy the text programmatically with in the browser. We use to rely on flash to get it done. Good news, now we have more than couple of ways to interact with clipboard using JavaScript.

Clipboard is a data buffer which is used to store the data for a short-period of time to perform operations like cut, copy and paste. Here are the ways that you can choose to operate with clipboard for cut, copy and paste operations.

Interact with clipboard using document.execCommand

document.execCommand API allows us to run commands on editable regions like form inputs and contenteditable elements. Visit commands of document.execCommand to find out all supported commands. We would use commands “copy”, “cut” and “paste” to interact with system clipboard.

document.execCommand is an old API compared to Async Clipboard API yet supported by most browsers.

Using document.execCommand for cut, copy & paste operation is limited to copying the selected text only

All document.execCommand calls must take place inside short-living event handlers of user actions like mouse click, keypress etc. Any kind of special permission is not required if document.execCommand is executed inside event handlers(as a result of user action, ex: mouse click). If it is called outside the event handlers, behavior depends on browser implementation, on Firefox this command will not execute and you will see error in the console

document.execCommand(‘cut’/‘copy’) was denied because it was not called from inside a short running user-generated event handler.

Copying text of given element using command.execCommand

Let’s see how to copy textContent of a given element using command.execCommand

function copyContent(elementID) {
const ele = document.getElementById(elementID);;

// Assume id of button is copy and id of input element is input
document.querySelector("#copy").addEventListener("click", e => copyContent("input"))

As you can see above code, we have selected content of given element first then called document.execCommand(‘copy’) to copy followed by blur to deselect text.

Cut content from input or contentEditable elements

Process is same as copy but pass “cut” as an argument instead of “copy” to document.execCommand function call.

function cutContent(elementID) {
const ele = document.getElementById(elementID);;

// Assume id of button is cut and id of input element is input
document.querySelector("#cut").addEventListener("click", e => cutContent("input"))

The paste command document.execCommand(‘paste’) is not supported by most of the browsers because of possible security concerns

See the Pen Clipboard document.execCommand by neotam (@neotam) on CodePen.

Copy text to clipboard using document.execCommand

If you want to put some random text into clipboard instead of selected content of the element, you have to create a temporary element, append it to document body, select it and then execute copy command. Since document.execCommand(‘copy’) only copies selected text /nodes from the DOM.

function copyToClipboard(text){
const ele = document.createElement('textarea');
ele.value = text;
ele.setAttribute('readonly', true)
// Following styling is to avoid flashing textarea on screen = 'absolute'; = 0; = 'transparent'; = 'none'; = '-100%';
const textToCopy = "Hello! I got Copied";
document.getElementById('copy').addEventListener('click', e => copyToClipboard(textToCopy))

See the Pen clipboard document.execCommand copyToClipboard by neotam (@neotam) on CodePen.

Asynchronous Clipboard API

This is recent addition to the specification, which seems more matured. Async clipboard API provides asynchronous access to the clipboard to read and write text directly so called Async Clipboard API . Unlike document.execCommand this one need permissions to interact with clipboard

This Clipboard (Async Clipboard API) only works in secure context, i.e only on HTTPS

Navigator exposes the system clipboard through property Navigator.clipboard

All methods of Clipboard or navigator.clipboard returns Promise . Which will be resolved if operation on clipboard is successful else it will rejected if there is any kind of error or clipboard access is denied because of permissions.

Following are PermissionNames related to Async Clipboard API, which are passed to navigator.permissions.query to request or check the permission.

  • clipboard-write
  • clipboard-read

Write to clipboard using navigator.clipboard

Clipboard has following two method to write data/text into clipboard

  • write()
  • writeText()

These methods trigger asynchronous operation and returns Promise which will be resolved on success else rejected on failure(possible if access denied)

Following simple function demonstrates using of navigator.clipboard which takes text and writes into the clipboard.

function writeToClipboard(text) {
result => {
console.log("Successfully copied to clipboard", result)
err => {
console.log("Error! could not copy text", err)

You can use the above function directly or you can wrap another function around it which tests for (permissions)access before calling this function

Checkout above code in action at write to clipboard using Async Clipboard API

Read from clipboard using navigator.clipboard

navigator.clipboard(Clipboard) has following two methods which are used for reading data/text from clipboard

  • read
  • readText

This following function uses navigator.clipboard.readText to read copied text from clipboard. Browser might prompt the user for permission to grant access to clipboard to read text.

Clipboard Events

We can listen for the “copy”, “cut” and “paste” events on document to override what is being copied and what is being pasted. This is useful when you want to apply formatting(or filter) to text while it goes to clipboard or comes out of clipboard

Override the copy event

document.addEventListener('copy', function(e) {
e.clipboardData.setData('text/plain', 'Hello! Welcome');
e.clipboardData.setData('text/html', '<b>Hello, Its copy override!</b>');

Override the cut event

document.addEventListener('cut', function(e) {

e.clipboardData.setData('text/plain', 'Hello! Welcome');
e.clipboardData.setData('text/html', '<b>Hello, Its copy override!</b>');

//Since we are overriding cut operation and preventing default we need
// to manullay remove the selecte text

Override the paste event

document.addEventListener('paste', function(e) {
if (e.clipboardData.types.indexOf('text/html') > -1) {
var oldData = e.clipboardData.getData('text/html');
var newData = '<b>Oh Yeah!</b> ' + oldData;

To prevent user from performing copy, cut and paste operation on particular element. Add “return false” to event handlers on that corresponding element.

<div oncopy="return false" oncut="return false" onpaste="return false"> </div>

Clipboard Library

If you are a library freak and don’t mind using Vanilla JavaScript . Here is the clipboard library for you

Install Javascript clipboard library using npm

npm install clipboard --save 

How to use this library is out of scope of this article. I will leave it to you, you may find more if you head over to npm clipboard

Leave a Reply

Your email address will not be published. Required fields are marked *