DEV Community

Nathan
Nathan

Posted on • Originally published at natclark.com

Copying Text to the Clipboard in JavaScript

The Clipboard API now has impressive browser support.

One way that we can interact with it is through the browser's window.navigator interface.

So, here is a simple function that uses the clipboard's writeText() method to copy any given string of text to the user's clipboard:

const copyText = (text) => {
    if (!navigator.clipboard) return; // For unsopported browsers
    navigator.clipboard.writeText(text).then(() => {
        console.log(`Text copied.`);
    }).catch((e) => {
        console.log(`Error copying text:`, e);
    });
};
Enter fullscreen mode Exit fullscreen mode

If an unsupported browser is used or if there is an error with writeText(), then the text will not be copied.

Some consider confirmation in the UI on successful copy events to be a good practice. One example would be a brief alert that pops up for a few seconds saying something like "Text copied".

It's especially important to make sure that you only modify the user's clipboard with their explicit permission.

Conclusion

I hope you enjoyed this quick little tutorial!

It's a simple snippet that I use, on average, probably about once a week.

Top comments (0)