How to copy to the clipboard with JavaScript

How to copy to the clipboard with JavaScript

Photo by Eco Warrior Princess

If you want to copy to the clipboard the text from an input element with JavaScript you can call the ​select ​function on the HTML element and then execute the copy command on the document.

//  <input id="myInput" type="text">
document​.​querySelector​(​'#myInput'​).​select​();
document​.​execCommand​(​'copy'​);

This works by selecting the text inside the input element (works for textarea and similar elements too) and calling the copy command on the document object.

But what if you want to copy some text that's not in an input element?

If the browser you’re working with supports it, you could also use the clipboard API found on the navigator object.

window​.​navigator​.​clipboard​.​writeText​(​'Some text'​);

Depending on the browser you are using, the user might also have to provide permission for you to directly write text to the clipboard although this usually isn't necessary when working in a secure context i.e. HTTPS.

Browser support for the Clipbboard API's writeText function is pretty good although Internet Explorer is not supported.

Watch the tutorial for more details.

Follow me on Twitter (@codebubb) for more tutorials.