TIL: Copying to the clipboard from a webpage is easy now

#til #webdev #javascript #clipboard

I remember a time when there were whole libraries dedicated to clipboard management.

Turns out in browsers released after ~2020 you can do it with one line:

navigator.clipboard.writeText(text).then(console.log).catch(console.error);

Some caveats:

Usually when I do this I'm implementing something like a “copy to clipboard” button:

<span id='copy-target'>This text is going into a clipboard</span>
<button onclick='copyToClipboard("copy-target")'>Copy</button>
<script>
    const copyToClipboard = (target) => {
        const element = document.getElementById(target);
        const value = element?.innerText
        if (value) {
            navigator.clipboard.writeText(value).then(console.log).catch(console.error);
        }
    }
</script>