How to Copy Text To Clipboard Using Javascript

Furkan is a software engineer and frontend developer, whose main purpose is to create best optimal experience for user but also keeping the application or project as performant as possible.
He is deeply interested on web technologies and he is building new projects in this subject. He is especially familiar with React, Vue, Node and Java. You can check out what he built on his GitHub account. There is potential ways to connect with him at the end of this summary 👇
Things he like to do; ✔ Trying to solve other people's struggles ✔ Teaching or telling some subject he know to friends or colleagues ✔ Building different kinds of projects ✔ Meeting & talking with new people ✔ Listening podcasts ✔ Playing Chess ✔ Watching drama | sci-fi movies ✔ Listening music while I travelling or trying to fix problems ✔ Researching next generation technologies like cyptocurrency, IoT, smart devices
If you want to reach out with him, here is how you can do it;
🔼 Blog: https://blog.furkanozbek.com/ 🔼 GitHub: https://github.com/afozbek 🔼 Mail: abdullah.furkan.ozbek@gmail.com 🔼 Twitter: https://twitter.com/afozbek_ 🔼 Instagram: https://instagram.com/furkan.codes/
Thanks for reading ✨
1. document.execCopy
We can use document.execCopy which has widely browser support. One important to notice is that it is right now deprecated.
- Access is synchronous
- Text is read from the DOM and placed on the clipboard.
- Good browser support
function fallbackCopyTextToClipboard(text) {
var textArea = document.createElement("textarea");
textArea.value = text;
// Avoid scrolling to bottom
textArea.style.top = "0";
textArea.style.left = "0";
textArea.style.position = "fixed";
document.body.appendChild(textArea);
textArea.focus();
textArea.select();
try {
var successful = document.execCommand('copy');
var msg = successful ? 'successful' : 'unsuccessful';
console.log('Fallback: Copying text command was ' + msg);
} catch (err) {
console.error('Fallback: Oops, unable to copy', err);
}
document.body.removeChild(textArea);
}
2. Navigator.clipboard.writeText
The Clipboard API adds to the Navigator interface the read-only clipboard property, which returns the Clipboard object used to read and write the clipboard's contents.
- writeText is used for writing contents to clipboard.
- Access is asynchronous and uses promises.
- Only supported on pages served over HTTPS.
navigator.clipboard.writeText(text).then(
function() {
console.log("Async: Copying to clipboard was successful!");
},
function(err) {
console.error("Async: Could not copy text: ", err);
}
);




