«   Previous tip Next tip   »

JavaScript: How to copy to the clipboard in JavaScript

1st July 2020

There's a Clipboard API for reading and writing to the clipboard, no plugins are needed. It's asynchronous and better for performance than the old technique.

Also note, reading from the clipboard prompts a permission dialog.

The actual code for copying text into the users clipboard is this:

The code

await navigator.clipboard.writeText('hello world')

Optionally, you can get the contents of the users clipboard with this:

await navigator.clipboard.readText() // hello world

Browser support

If you want better browser support, you can use:

document.execCommand('copy')

However the code above is synchronous which could block the JavaScript main thread, especially when copying a very large string to the users clipboard, or even reading from the clipboard.

«   Previous tip Next tip   »

Sign up to receive a developer tip, in the form of a gif, in your inbox each week