How to Copy Text to the Clipboard with JavaScript using the Clipboard API
Content Index
- What does copying to the clipboard in JavaScript mean?
- Using navigator.clipboard.writeText
- Why is it a promise?
- Security considerations: HTTPS and browser permissions
- Browser compatibility
- Improving the user experience (UX)
- Common errors and how to solve them
- Frequently Asked Questions (FAQ)
- Conclusion
- How to copy content to the clipboard with JavaScript
- Browser Support
- 1.0 Capturing a computer screen
-
2.0 Saving the screenshot in an
element with JavaScript
- 2.1 The paste event in JavaScript
- 2.2 Defining our function to capture the event
- 2.3 Explaining the previous function…
- ClipboardEvent.clipboardData to read clipboard data
- 2.4 Final result of the experiment
- 3. Sending the image copied from the clipboard to the server with Ajax
- 3.1 Saving the image on the server
- 3.2 Generating a base64 encoded string of the image on the server
- The objet FileReader()
- 3.3 How to save the image in base64 in our database?
- Considerations
Copying text to the clipboard from a web page may seem like a basic thing, but behind it lies a modern API and a series of important security considerations. In this guide, I'll show you how to implement this functionality in JavaScript, with real examples, cross-browser compatibility, and some tricks I learned while applying it to 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 very important point: we are accessing the operating system using JavaScript.
I show you how you can modify the clipboard, that is, how to implement the copy and paste functionality using JavaScript.
What does copying to the clipboard in JavaScript mean?
When we copy something—be it text, a link, or a code snippet—we are modifying the operating system's clipboard. This involves a small "conversation" between the browser and the OS, something that JavaScript can do using the Clipboard API.
In my case, the first time I needed this functionality was to allow users to copy code snippets with a click. For this, document.execCommand('copy') is used, since that method is obsolete. The modern and safer solution is navigator.clipboard.writeText().
Using navigator.clipboard.writeText
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 directly interacts with the operating system.
navigator.clipboard.writeText("Tu texto aquí");This method receives the text you want to copy, and since it is an operation that interacts with the operating system (something that could be busy or require permissions), it works as a promise.
Why is it a promise?
Every time we access the disk or the operating system from JavaScript, a promise is used because those operations are not resolved immediately.
That's why here we are also using a promise, which resolves when the text has been successfully copied to the clipboard. If you want to do something once it has been copied, you can use .then(), just as I do, where I show a small toast to notify the user that the action is complete:
btn.addEventListener('click', () => {
this.$toast.success(this.$t('resource.copied') + "!");
const text = pre.innerText;
navigator.clipboard.writeText(text).then(() => {
// btn.innerText = this.$t('resource.copied');
this.$toast.success(this.$t('resource.copied') + "!");
}).catch(err => {
console.error('Error al copiar: ', err);
});
});Security considerations: HTTPS and browser permissions
A couple of things you should keep in mind:
- You must be on **HTTPS** for this to work correctly. For example, if you work on localhost with HTTPS (like https://localhost), you won't have problems.
- However, if you are in an **insecure environment**, such as a virtual host with http (without the "s"), you will see an error like the one I show on the screen:
navigator.clipboard is null
- This happens because browsers block access to the clipboard in insecure environments. In my case, the first time I tested it in a local environment with HTTP, the method simply didn't respond. When activating HTTPS, everything worked correctly.
Browser compatibility
If you're worried that the user's browser is old or doesn't support this API, you can do a simple validation like this:
if (navigator.clipboard) {
// puedes usar clipboard.writeText
} else {
// muestra un mensaje alternativo
}With this, you can copy and paste content easily using JavaScript and offer a better user experience, as long as you respect the security requirements.
Improving the user experience (UX)
Beyond it working, it's important that the user knows the text was copied correctly. You can show a message, change the button's text, or launch a small toast.
Another improvement is using **async/await**, which makes the code cleaner:
async function copiarTexto() {
try {
await navigator.clipboard.writeText("Texto copiado con éxito");
alert("Texto copiado al portapapeles ✅");
} catch (err) {
console.error("No se pudo copiar:", err);
}
}You can also copy automatically when the page loads or on a double-click, although this should be done with caution, as some browsers block it if there's no direct user interaction.
Common errors and how to solve them
Error Probable Cause Solution
navigator.clipboard is undefined Page without HTTPS or insecure context Use HTTPS or localhost environment
Promise rejected Permission denied or browser block Retry after user interaction
Nothing is copied Code executed outside of a user event Execute inside a click or input
In my experience, the most common error is executing the function before the user interacts. For security, most browsers don't allow copying without explicit action.
Frequently Asked Questions (FAQ)
- Why doesn't navigator.clipboard work on HTTP?
- Because browsers only enable the Clipboard API on HTTPS sites or on localhost.
- Which browsers support clipboard.writeText()?
- Most modern browsers, except Internet Explorer.
- How can I show a message when the text is copied?
- You can use alert(), a toast, or change the button's text after copying.
- What's the difference between execCommand('copy') and clipboard.writeText()?
- execCommand is an old and less reliable API; clipboard.writeText is the modern and secure method.
Conclusion
Copying text to the clipboard with JavaScript is a small but powerful functionality. By using navigator.clipboard.writeText(), you can offer a smooth, secure, and modern experience.
In my case, applying this technique in my projects significantly improved user interaction; on the Academia website, I implemented it so the user can copy codes with a single click.
How to copy content to the clipboard with JavaScript
In this entry we will see how to copy text that is set in our HTML to our clipboard using JavaScript without the need to use Flash or any third-party technologies.
In this entry we will see how to copy a text that is established in our HTML to our clipboard using JavaScript without the need to use Flash or any third-party technology.
The clipboard is nothing more than a tool of the operating system that allows you to store data such as texts and images.
The clipboard is generally accessed using the combination Ctrl + C to copy and Ctrl + V to paste.
We will create a simple function whose core is the method called execCommand that allows executing commands to the current document with the current selection, this may sound a bit confusing but it is actually quite an easy function.
With what was said above, and for it to work we must have a hidden text field or another that allows us to create a selection field which is the current selection field that we will use to empty the text that we want to copy to the clipboard that will then be copied. via the execCommand method with the "copy" parameter; without going any further the function:
function copiar(id_elemento) {
// Crea un campo de texto "oculto"
var aux = document.createElement("input");
// Asigna el contenido del elemento especificado al valor del campo
aux.setAttribute("value", document.getElementById(id_elemento).innerHTML);
// Añade el campo a la página
document.body.appendChild(aux);
// Selecciona el contenido del campo
aux.select();
// Copia el texto seleccionado
document.execCommand("copy");
// Elimina el campo de la página
document.body.removeChild(aux);
console.log("texto copiado")
}You can put the previous script to good use by creating a text field with editable content as we have seen above in: HTML editable sections with the contenteditable attribute.
Browser Support
Before using the command document.execCommand("copy"); it is good practice to check for browser support; To do this we use the following command:
document.queryCommandSupported('copy');| Navegador | Versión |
|---|---|
| Internet Explorer | 10+ |
| Google Chrome | 43+ |
| Firefox | 41+ |
| Opera | 29+ |
| Safari | (sin soporte) |
In this entry we will see how to copy an image from a screenshot that is temporarily saved on the clipboard or clipboard in an <img> element.
We will also see how we can send this image through Ajax for processing and saving on the server; Below is the table of contents:
- Capturando la pantalla de un ordenador
- Guardando la captura de pantalla en un elemento con JavaScript
- Enviando la imagen copiada del clipboard al servidor con Ajax
1.0 Capturing a computer screen
Many Linux distributions such as Fedora offer applications from which we can take screenshots:

That allow you to save an image resulting from the screenshot to some location on the computer or on the clipboard; the latter is part of our case of interest.
You can also use the F12 key or the PrintScreen key provided on many keyboards; although these actions may not copy the image to the clipboard or may not even work on certain operating systems.
2.0 Saving the screenshot in an <img> element with JavaScript
Once we have taken the screenshot to the clipboard, we must define an event that allows us to capture the moment when we copy some content to a website using:
- The Ctrl + V combination on our keyboard.
- Selecting the paste option from our browser.
- In the pop-up menu, click on the paste option.
2.1 The paste event in JavaScript
The JavaScript API provides an event that allows you to capture the paste event through the following line of code:
window.addEventListener("paste", pasteEvent);2.2 Defining our function to capture the event
Now we can define the function called pasteEvent() that will be executed when any of the events mentioned above occur; this function allows you to copy the contents of the clipboard into an element of type <img>; Let's see the complete definition of the function:
window.addEventListener("paste", processEvent);
function processEvent(e) {
for (var i = 0; i < e.clipboardData.items.length; i++) {
// get the clipboard item
// obtengo el clipboard item
var clipboardItem = e.clipboardData.items[0];
var type = clipboardItem.type;
// verifico si es una imagen
if (type.indexOf("image") != -1) {
// obtengo el contenido de la imagen BLOB
var blob = clipboardItem.getAsFile();
console.log("blob", blob);
// creo un la URL del objeto
var blobUrl = URL.createObjectURL(blob);
console.log("blobUrl", blobUrl);
// agrego la captura a mi imagen
document.getElementsByTagName("img")[0].setAttribute("src", blobUrl);
} else {
console.log("No soportado " + type);
}
}
}2.3 Explaining the previous function…
ClipboardEvent.clipboardData to read clipboard data
The clipboardData object allows access in read-only mode to the data contained in the clipboard through an Array of items; we can also find the type of data (which can be text, images, etc.) that is in a certain position of the Array.
var clipboardItem = e.clipboardData.items[i];Once we have the item to evaluate; we determine the type of data and the stored data respectively:
- We query the type through the type type.indexOf("image") method.
- We obtain the BLOB data (raw data) through the getAsFile() method clipboardItem.getAsFile().
After inspecting the data type and obtaining the same, it is necessary to convert the data from a BLOB object to a DOMString using the createObjectURL() method that creates a URL that represents the object, so that the image can be rendered into an element of type <img>:
var blobUrl = URL.createObjectURL(blob); Finally we copy the content of the image from the screenshot into an <img> element:
img.attr("src", blobUrl);2.4 Final result of the experiment
Copy the image you have to the clipboard with Ctrl + V or another mode.
3. Sending the image copied from the clipboard to the server with Ajax
3.1 Saving the image on the server
A useful use of the experiment presented above is to be able to save the image already generated and saved in an <img> element on the server; For this we can use Ajax or a form in the traditional way; although before we can save the image on the server we must process it so that it can be handled correctly.
3.2 Generating a base64 encoded string of the image on the server
At this point, if we check the source src attribute of the image:

We will realize that it is nothing more than a value that represents our image, but it does not offer us any information about it; In order to save an image on the server, it is not possible to use a BLOB type or the URL that represents it; We must encode it in base64 so that the image can be easily processed from the server.
We can easily convert our image from a BLOB type to base64 with the following script:
var reader = new window.FileReader();
reader.readAsDataURL(clipboardItem.getAsFile());
reader.onload = function() {
console.log(reader.result.replace('data:image/png;base64,', '')
.toString()
$.ajax({
type: 'POST',
url: URL,
data: {
'pantalla': reader.result
.replace('data:image/png;base64,', '').toString(),
},
success: function(response) {}
});
}The objet FileReader()
First we create an object of type FileReader() that allows reading files asynchronously.
Once the file (our image) is read, the result property will read the contents of the file/image already encoded in base64.
Once our image has been encoded, it is possible to send the image encoded in base64 by Ajax or through a field in a form.
3.3 How to save the image in base64 in our database?
Once our base64 encoded image is obtained on the server side, it must be decoded; If we use Java Web we can use the following function to decode the base64 image to a byte array:
byte imagen[] = Base64.decodeBase64(imageString);In PHP there is a similar function:
$data = base64_decode($data);Once the image is decoded, the database can be saved as if it were any other file obtained from the server by a file type input.
Considerations
Depending on the decoding function to be used, it may be necessary to remove the data:image/png;base64 header present in our base64-encoded image; this applies to the Base64.decodeBase64 function in Java; if this header is left, the image could be decoded with errors and therefore the file would be corrupted.
I agree to receive announcements of interest about this Blog.
How to use navigator.clipboard.writeText() to copy text to the clipboard in JavaScript. Learn best practices, common mistakes, and browser support.