How to copy text to the clipboard (and read it) in JavaScript

OpenJavaScript 0

Last updated: January 31, 2023.

You can easily copy text to the clipboard in JavaScript by using the Clipboard API on the window.navigator object.

Table of contents

Copying to the clipboard

To copy text to the clipboard, simply call the writeText() method available on window.navigator.clipboard, while passing in some text to commit to the clipboard:

/* Copying text to the clipboard */

navigator.clipboard.writeText("My text");

Often, you may want to have multipe page elements that trigger text to be copied, so it is best to create a dedicated function that can be called, passing in the text to copy:

/* Reusable function for copying text to the clipboard */

function copyToClipboard(myText) {
    navigator.clipboard.writeText(myText);
}

copyToClipboard("My text");

Result-handling

Calling writeText() returns a promise object that can be used for result-handling.

Using original promises syntax, the result can be handled by chaining .then() and .catch() methods, defining a function within each.

If copying was successful, the function inside then .then() and, in case of an error, the function inside .catch() is triggered:

/* Handling the returned promise object */

function copyToClipboard(msg) {
    navigator.clipboard.writeText(msg)
      .then(() => alert(`Copied "${msg}" successfully`))
      .catch((err) => alert("Copy failed: "+ err));
}

copyToClipboard("Text to copy");

A more modern approach is to use async/await syntax to handle the result, which results in less nesting because the keyword await can be used to wait for the result of anything that returns a promise object:

/* Handling the promise object with async/await */

async function copyToClipboard(msg) {
  try {
    await navigator.clipboard.writeText(msg);
    alert(`Copied "${msg}" successfully`);
  } catch {
    alert("Copy failed: "+ err);
  }
}

copyToClipboard("Text to copy");

Reading text from the clipboard

Reading text from the clipboard is unreliable in modern browsers. It is not supported at all in Firefox.

Note that if readText() can be used, most modern browsers will warn the user that an attempted copy of the contents of their clipboard is being made.

You can attempt to read the contents of the clipboard by calling navigator.clipboard.readText() method:

/* Reusable function for reading the clipboard */

function readClipboard() {
    navigator.clipboard.readText();
}

readClipboard("My text");

Result-handling

Like copyText(), readText() also returns a promise that can be used to handle the result using.then() and .catch() syntax.

If successful, the parameter available in the function defined in .then() will contain the contents of what was read:

/* Handling the result of reading the clipboard */

function readClipboard() {
    navigator.clipboard.readText()
    .then(res => alert("Success! Read: " + res)) // Will alert what was copied
    .catch(err => alert("Failed to read the clipboard: " + err));
}

readClipboard();

Alternatively, the result can be handled using async/await:

/* Handling the result using async/await */

async function readClipboard() {
    try {
        await navigator.clipboard.readText();
        alert("Success! Read: " + res)
    } catch {
        alert("Failed to read the clipboard: " + err);
    }
}

readClipboard();

Is readText() ever useful?

One practical reason you may consider using readText() is to check if writeText() has worked successfully. But, because of the unreliability of the readText() method, it is better to rely on promise-handling for this purpose.

Summary

The writeText() method available on window.navigator.clipboard makes it easy to copy text to the clipboard in JavaScript. The result can then be handled using .then() and .catch() or async/await syntax.

Though possible in some browsers, it is generally not advised to rely upon the readText() method for reading the contents of the clipboard due to unreliability.

Related posts: