Skip to content

Instantly share code, notes, and snippets.

@giladno
Created June 21, 2021 21:33
Show Gist options
  • Save giladno/dd936a1737d10d06271f3869d5902369 to your computer and use it in GitHub Desktop.
Save giladno/dd936a1737d10d06271f3869d5902369 to your computer and use it in GitHub Desktop.
Copy to clipboard in js
export function copy (text) {
if (window.clipboardData && window.clipboardData.setData) {
return window.clipboardData.setData("Text", text);
} else if (document.queryCommandSupported && document.queryCommandSupported("copy")) {
var textarea = document.createElement("textarea");
textarea.textContent = text;
textarea.style.position = "fixed";
document.body.appendChild(textarea);
textarea.select();
try {
document.execCommand("copy");
return true;
} catch (ex) {
console.warn("Copy to clipboard failed.", ex);
return false;
} finally {
document.body.removeChild(textarea);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment