Last active
April 19, 2023 20:00
-
-
Save jrc03c/449519773f11e554df777d9cda67e147 to your computer and use it in GitHub Desktop.
Copy arbitrary text to the clipboard in the browser
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// π¨ π¨ π¨ | |
// 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