Copying Text to the Clipboard with JavaScript — Clipboard API and navigator.clipboard.writeText()

- Andrés Cruz - ES En español

Video thumbnail

Copying text to the clipboard from a webpage might seem like a basic thing, but behind it lies an entire modern API and a series of important security considerations. In this guide, I will show you how to implement this functionality in JavaScript, with real examples, cross-browser compatibility, and some tips I learned while applying it in my own projects.

When we copy something from an application or a website, we are modifying our operating system's clipboard — and here comes a key point: we are accessing the OS directly from JavaScript, which implies permissions, secure context, and asynchronous operations.

I will show you how to modify the clipboard and implement copy and paste functionality using JavaScript, from the modern method with the Clipboard API to the legacy approach with execCommand.

Previously we looked at how to use Drag and Drop in HTML and JavaScript.

What does copying to the clipboard mean in JavaScript?

When we copy something — whether it's text, a link, or a snippet of code — we are modifying the operating system's clipboard. This involves a small "conversation" between the browser and the OS, something JavaScript can do via the Clipboard API.

The clipboard is nothing more than an operating system tool that allows temporarily storing data like text and images. It is usually accessed with the Ctrl + C combination to copy and Ctrl + V to paste; but from JavaScript we can control it programmatically.

The first time I needed this functionality was to allow users to copy code snippets with a click on my academy platform. I started using document.execCommand('copy'), but that method is deprecated and its behavior varies across browsers. The modern, secure, and recommended solution today is navigator.clipboard.writeText().

Using navigator.clipboard.writeText(): the modern method

The Clipboard API offers a simple and secure way to copy text to the clipboard. The navigator.clipboard.writeText() method receives the text you want to copy and returns a promise, because it is an asynchronous operation that interacts directly with the operating system.

navigator.clipboard.writeText("Your text here");

Why does it return a promise?

Every time we access disk, the operating system, or device resources from JavaScript, a promise (Promise) is used, because those operations do not resolve instantaneously. The browser needs to verify permissions, communicate with the OS, and wait for confirmation before completing the write.

That's why navigator.clipboard.writeText() is also asynchronous: it resolves when the text has been successfully copied. If you want to execute something right after — like notifying the user — you can chain it with .then():

btn.addEventListener('click', () => {
  const text = pre.innerText;
  navigator.clipboard.writeText(text).then(() => {
    this.$toast.success(this.$t('resource.copied') + "!");
  }).catch(err => {
    console.error('Error copying: ', err);
  });
});

In the previous example, I capture the text from the pre element using innerText and, after successfully copying it, I show a confirmation toast to the user. The .catch() block is essential: without it, silent errors can confuse both the developer and the user.

Version with async/await: cleaner code

An alternative that makes the code more readable is to use async/await with a try/catch block:

async function copyText(text) {
  try {
    await navigator.clipboard.writeText(text);
    alert("Text copied to clipboard ✅");
  } catch (err) {
    console.error("Could not copy:", err);
  }
}

Both ways — .then()/.catch() and async/await — are valid. I personally prefer async/await when the logic following the copy is more extensive, as it avoids callback nesting.

Security considerations: HTTPS and browser permissions

The Clipboard API has strict security requirements that you should know before implementing it:

  • Only works in secure contexts: the page must be served under HTTPS. In local development, https://localhost is also allowed, but a virtual host with http:// (without the "s") is not.
  • If you try to use the API in an insecure environment, you will get an error similar to this:

    navigator.clipboard is null

    or even navigator.clipboard is undefined, depending on the browser.

  • Must execute within a user event: browsers block clipboard access if the call is not originated by a direct user action, such as a click or keydown. Trying to copy automatically upon page load, for example, usually fails for this reason.
  • The first time the user visits the page, the browser might request explicit permission confirmation to access the clipboard (especially when reading from it with clipboard.readText()).

In my case, the first time I tried it in a local environment with HTTP, the method simply did not respond. Upon activating HTTPS, everything worked correctly right away.

Browser compatibility

navigator.clipboard.writeText() is supported in all modern browsers: Chrome, Firefox, Edge, Opera, and Safari (since version 13.1). The only notable exception is Internet Explorer, which does not support the modern Clipboard API.

To check at runtime whether the user's browser supports the API before calling it, you can make this check:

if (navigator.clipboard) {
  // you can use navigator.clipboard.writeText()
  navigator.clipboard.writeText("Copied text");
} else {
  // show an alternative message or use the legacy method
  console.warn("Clipboard API not supported in this browser.");
}

Improving User Experience (UX)

Beyond technical functionality, it's important for the user to know that the text was copied successfully. Some strategies that work well:

  • Show a temporary confirmation toast or notification.
  • Change the button text from "Copy" to "Copied!" for a few seconds.
  • Add a check icon (✅) as immediate visual feedback.

For example, to change the button text temporarily:

async function copyWithFeedback(btn, text) {
  try {
    await navigator.clipboard.writeText(text);
    btn.textContent = "Copied! ✅";
    setTimeout(() => { btn.textContent = "Copy"; }, 2000);
  } catch (err) {
    console.error("Error copying:", err);
  }
}

You can also trigger the copy on double-click, although this should be done with caution: some browsers block clipboard access if there is no direct interaction recognized by the browser engine.

Common errors and how to solve them

ErrorProbable causeSolution
navigator.clipboard is undefinedPage without HTTPS or non-secure contextUse HTTPS or localhost
Rejected promise (permission denied)Permission denied or browser blockRetry after direct user interaction
Nothing copies / no visible errorCode executed outside of a user eventExecute inside a click or input
navigator.clipboard is nullHTTP environment (without SSL)Enable HTTPS on your server or local environment

In my experience, the most common error is executing the function before the user interacts. For security, most modern browsers do not allow accessing the clipboard without explicit user action.

Frequently Asked Questions (FAQ)

  • Why does navigator.clipboard not work on HTTP?
    • Because browsers only enable the Clipboard API on sites with HTTPS or on localhost. This is a security measure to prevent malicious scripts from accessing the user's clipboard without consent.
  • What browsers support clipboard.writeText()?
    • Chrome 66+, Firefox 63+, Edge 79+, Opera 53+, and Safari 13.1+. The major exception is Internet Explorer, which has no support.
  • How can I show a message when the text is copied?
    • You can use alert(), a toast, change the button text, or any other visual mechanism. The most recommended is a non-intrusive message that disappears automatically.
  • What is the difference between execCommand('copy') and clipboard.writeText()?
    • execCommand is an old, deprecated API with inconsistent behavior across browsers. clipboard.writeText() is the modern, asynchronous, secure method backed by the W3C standard. You should always prefer the latter.
  • Can I read the clipboard with JavaScript?
    • Yes. The Clipboard API also offers navigator.clipboard.readText() to read the clipboard contents, although this method requires explicit user permission and only works over HTTPS.
  • Can I copy to the clipboard in JavaScript without HTTPS?
    • Not with the modern Clipboard API. As a last-resort alternative, you can use the legacy method with document.execCommand('copy'), although it is not recommended for new projects.

Conclusion

Copying text to the clipboard with JavaScript is a small yet powerful functionality. Using navigator.clipboard.writeText() you can offer a smooth, secure, and completely modern experience without external dependencies.

In my case, applying this technique in the Academy platform noticeably improved user interaction: I implemented a "Copy code" button on every code block, and the response was very positive. With a single click, the user already has the snippet in their clipboard.

Below I also leave the legacy approach with execCommand for your reference, especially if you need to support older environments.

Legacy method: copying to the clipboard with document.execCommand('copy')

Before the existence of the Clipboard API, the way to copy content to the clipboard from JavaScript was via the document.execCommand('copy') method. This method, although deprecated nowadays, still works in many browsers and can be useful as a fallback for environments without HTTPS.

The trick consists of creating a hidden text field, assigning it the value we want to copy, selecting it programmatically, and then executing the copy command:

function copy(id_element) {
  // Creates a temporary text field
  var aux = document.createElement("input");
  // Assigns the element's content to the field's value
  aux.setAttribute("value", document.getElementById(id_element).innerHTML);
  // Adds the field to the DOM
  document.body.appendChild(aux);
  // Selects the field's content
  aux.select();
  // Executes the copy command
  document.execCommand("copy");
  // Removes the temporary field from the DOM
  document.body.removeChild(aux);
  console.log("text copied");
}

Before using document.execCommand("copy"), it is good practice to check if the browser supports it via:

document.queryCommandSupported('copy');
BrowserexecCommand('copy') Support
Internet Explorer10+
Google Chrome43+
Firefox41+
Opera29+
SafariNo support

You can combine this method with an editable text field, as seen in: Editable sections in HTML with the contenteditable attribute.

View example

Reading images from the clipboard with JavaScript: the paste event

View example Download source

The Clipboard API not only allows copying text: we can also intercept images from a screenshot that the user has saved in their clipboard, and display them directly in an <img> element on the page.

Additionally, we will see how to send that image to the server via Ajax to process and save it. Below is the table of contents:

  1. Capturing a computer screen
  2. Saving the screenshot into an element with JavaScript
    1. The paste event in JavaScript
    2. Defining our function to capture the event
    3. Explaining the previous function...
  3. Sending the copied clipboard image to the server with Ajax
    1. Saving the image on the server
    2. Generating a base64 encoded string of the image on the server
    3. How to save the base64 image in our database?

1.0 Capturing a computer screen

Many Linux distributions like Fedora include built-in tools to take screenshots:

application screenshot

These tools allow saving the image to a disk location or directly to the clipboard; the latter case is the one we are interested in.

You can also use the Print Screen key available on many keyboards, although its behavior varies: on some operating systems it saves the screenshot to the clipboard automatically, and on others it saves it directly to disk.

2.0 Saving the screenshot into an <img> element with JavaScript

Once we have the screenshot in the clipboard, we must listen for the moment the user pastes it into the webpage. This can happen in three ways:

  • The Ctrl + V combination on the keyboard.
  • Selecting the "Paste" option from the browser's context menu.
  • Using the popup menu (right click) and choosing the "Paste" option.

More information about the paste event on w3schools.

2.1 The paste event in JavaScript

JavaScript exposes the paste event which fires every time the user pastes content into the page. We can listen to it globally as follows:

window.addEventListener("paste", pasteEvent);

2.2 Defining our function to capture the event

We define the pasteEvent() (or processEvent()) function that will execute when the user pastes content. Inside it, we inspect the clipboard items to identify if there is an image and display it in an <img> element:

window.addEventListener("paste", processEvent);

function processEvent(e) {
    for (var i = 0; i < e.clipboardData.items.length; i++) {
        // Get the clipboard item
        var clipboardItem = e.clipboardData.items[0];
        var type = clipboardItem.type;
        // Verify if it is an image
        if (type.indexOf("image") != -1) {
            // Get the image content as BLOB
            var blob = clipboardItem.getAsFile();
            console.log("blob", blob);
            // Create a temporary object URL
            var blobUrl = URL.createObjectURL(blob);
            console.log("blobUrl", blobUrl);
            // Assign the image to the element 
            document.getElementsByTagName("img")[0].setAttribute("src", blobUrl);
        } else {
            console.log("Unsupported type: " + type);
        }
    }
}

2.3 Explaining the previous function...

ClipboardEvent.clipboardData: reading clipboard data

The clipboardData object allows read-only access to the data contained in the clipboard, exposed as an array of items. Each item has a data type (text, image, etc.) and the data itself:

var clipboardItem = e.clipboardData.items[i];

Once we have the item to evaluate, we determine the data type and process it:

  • We check the type via the type property and look for "image": type.indexOf("image").
  • We obtain the BLOB data (raw data) using the getAsFile() method: clipboardItem.getAsFile().

Once the BLOB data is obtained, we convert it to a temporary URL using URL.createObjectURL(), which creates a DOMString with a URL representing the object, allowing the image to be rendered in the <img> element:

var blobUrl = URL.createObjectURL(blob);

Finally, we assign that URL as the src attribute of the image element:

img.setAttribute("src", blobUrl);

2.4 Final result of the experiment

Copy an image to your clipboard (with Ctrl + C over an image, or with Print Screen) and then paste it onto the page with Ctrl + V. The image will appear rendered in the page's <img> element.

3. Sending the copied clipboard image to the server with Ajax

3.1 Saving the image on the server

Once we have the image rendered in the <img> element, the next step is to send it to the server to process and save it. For this we can use Ajax or a traditional form. However, before sending it we must convert it to a format the server can handle correctly: a string encoded in base64.

3.2 Generating a base64 encoded string of the image

If we inspect the image's src attribute after assigning the BLOB URL:

img src

We will see that the value is a blob:http://... type URL, which is a temporary reference to the object in memory. That format cannot be sent directly to the server or saved in a database; we need to convert the image to base64 first. We can do it with the FileReader API:

var reader = new window.FileReader();
reader.readAsDataURL(clipboardItem.getAsFile());

reader.onload = function() {
    var base64Data = reader.result
        .replace('data:image/png;base64,', '')
        .toString();

    $.ajax({
        type: 'POST',
        url: URL,
        data: {
            'pantalla': base64Data,
        },
        success: function(response) {}
    });
};

The FileReader() object

The FileReader object allows reading files asynchronously directly from the browser. By calling reader.readAsDataURL(), it converts the Blob into a base64 encoded data:URL string. Once reading is complete, the reader.result property contains that string ready to be processed.

Once the image is encoded, we can send it via Ajax or include it in a hidden form field.

3.3 How to save the base64 image in our database?

On the server side, we must decode the base64 string to get the image bytes. If you use Java Web, you can do it with:

byte[] imagen = Base64.decodeBase64(imageString);

In PHP, the equivalent function is:

$data = base64_decode($data);

Once decoded, the image can be saved to the database or file system just like any other file received through a file type input.

Important considerations

Depending on the decoding function you use on the server, it might be necessary to strip the data:image/png;base64, header from the string before decoding it. This applies especially to the Base64.decodeBase64 function in Java: if that header is not removed, the image will decode with errors and the file will be corrupted.

View example Download source

The next step: learn how to send native notifications with JavaScript.

Learn how to use navigator.clipboard.writeText() to copy text to the clipboard in JavaScript. Includes examples using async/await, HTTPS permission requirements, and reading images from the clipboard.


Únete a la comunidad de desarrolladores que han decidido dejar de picar código y empezar a construir productos reales. Recibe mis mejores trucos de arquitectura cada semana:

I agree to receive announcements of interest about this Blog.