Copy text to the clipboard

The modern clipboard API in three lines, with the gotchas.

SNP 031 #592 Filed js webdev

javascript
async function copy(text) {
  await navigator.clipboard.writeText(text)
}

Two things to know: it only works on HTTPS (and localhost), and it has to run in response to a user action like a click. Calling it on page load fails.

Show some feedback, people don't trust silent buttons:

javascript
button.addEventListener('click', async () => {
  await copy(code.textContent)
  button.textContent = 'Copied'
  setTimeout(() => (button.textContent = 'Copy'), 1500)
})

The copy buttons on the code blocks of this site do exactly that.