Copying Text to the Clipboard in JavaScript

- 1 minute read

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);
    });
};

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.

Link to this section Conclusion

I hope you enjoyed this quick little tutorial!

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