DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’» is a community of 966,155 amazing developers

We're a place where coders share, stay up-to-date and grow their careers.

Create account Log in
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.

Top comments (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!

This post blew up on DEV in 2020:

js visualized

πŸš€βš™οΈ JavaScript Visualized: the JavaScript Engine

As JavaScript devs, we usually don't have to deal with compilers ourselves. However, it's definitely good to know the basics of the JavaScript engine and see how it handles our human-friendly JS code, and turns it into something machines understand! πŸ₯³

Happy coding!