How to copy content to the clipboard with JavaScript

- Andrés Cruz

En español

How to copy content to the clipboard with JavaScript

Ver

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');
NavegadorVersión
Internet Explorer10+
Google Chrome43+
Firefox41+
Opera29+
Safari(sin soporte)

You can check the original experiment here Copiar el contenido de un elemento al portapapeles usando JavaScript

Ver

Andrés Cruz

Develop with Laravel, Django, Flask, CodeIgniter, HTML5, CSS3, MySQL, JavaScript, Vue, Android, iOS, Flutter

Andrés Cruz In Udemy

I agree to receive announcements of interest about this Blog.