DEV Community

Cover image for 馃搵 How to easily copy text to clipboard
J茅r么me Pott
J茅r么me Pott

Posted on

馃搵 How to easily copy text to clipboard

The Chrome team has recently extended the support of the Clipboard API. One improvement is the ability to easily copy text not present in the DOM:

let textToCopy = 'Copy me' 

async function copyToClipboard() {
  try {
    // 1) Copy text
    await navigator.clipboard.writeText(textToCopy);

    // 2) Catch errors
  } catch (err) {
    console.error('Failed to copy: ', err);
  }
}

Enter fullscreen mode Exit fullscreen mode

The new method navigator.clipboard.writeText is indeed much easier to use than the commonly used document.execCommand('copy') method:

let textToCopy = 'Copy me' 

function copyToClipboard() {
  // 1) Add the text to the DOM (usually achieved with a hidden input field)
  const input = document.createElement('input');
  document.body.appendChild(input);
  input.value = textToCopy;

  // 2) Select the text
  input.focus();
  input.select();

  // 3) Copy text to clipboard
  const isSuccessful = document.execCommand('copy');

  // 4) Catch errors
  if (!isSuccessful) {
    console.error('Failed to copy text.');
  }
}

Enter fullscreen mode Exit fullscreen mode

So what's the catch?

Well, navigator.clipboard is currently only available in Chrome 馃槩
It may take quite some time before browsers fully support this clipboard API. Allowing read & write access to the user's clipboard come with great security issues and browser vendors need time to do it right.

So for now, we're stuck with document.execCommand. Fortunately there are libraries like clipboard.js that save us the trouble.

More information and codepen

If you want to learn more about accessing the clipboard using Vanilla JavaScript, I recommend reading this informative post from alligator.io.

Inspired by that post, I also made a codepen showcasing a complete example using the new navigator.clipboard.

Discussion (3)

Collapse
antunesales profile image
antunesales

Thousand thanks!

Collapse
antunesales profile image
antunesales

You saved me! Thank you!

Collapse
melih profile image
Melih

That's exactly what I was looking for. Thanks a lot!