Skip to content

Instantly share code, notes, and snippets.

@jrc03c
Last active April 19, 2023 20:00
Show Gist options
  • Save jrc03c/449519773f11e554df777d9cda67e147 to your computer and use it in GitHub Desktop.
Save jrc03c/449519773f11e554df777d9cda67e147 to your computer and use it in GitHub Desktop.
Copy arbitrary text to the clipboard in the browser
// 🚨 🚨 🚨
// NOTE: According to MDN, `document.execCommand()` is deprecated. See:
// https://developer.mozilla.org/en-US/docs/Web/API/document/execCommand
// Instead, use the Clipboard API:
// https://developer.mozilla.org/en-US/docs/Web/API/Clipboard_API
// 🚨 🚨 🚨
function copy(text) {
const input = document.createElement("input")
input.type = "text"
input.value = text
input.addEventListener("click", () => {
input.select()
document.execCommand("copy")
input.removeEventListener("click", this)
document.body.removeChild(input)
})
document.body.appendChild(input)
input.click()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment