How To Copy To Clipboard Using JavaScript

Dec 26, 2020

User avatar


Scott Tolinski

This is going to be a quick one. At its most concise, copying from a text string to the user's clipboard is a one liner using a browser API "navigator.clipboard" You can learn much more about the ins and outs of the Clipboard here:

Without further adieu, here is the snippet.

navigator.clipboard.writeText("some string to be copied!")

This method returns a promise, so a practical use case might look something like this.

async function copyToClipboard(textToCopy) {
  try {
    await navigator.clipboard.writeText(textToCopy)
  } catch (e) {

Please do pay attention to compatibility listed on the MDN Docs, users needing to support IE11 are out of luck.