Ways to copy text to the clipboard in JavaScript

  1. Using the navigator.clipboard API: This is the recommended method. You can use the navigator.clipboard.writeText() method to write the text to the clipboard.
navigator.clipboard.writeText('Hello, World!').then(() => {
  console.log('Text written to clipboard');
});
  1. Using the copy() method: This method is supported in most browsers. However, it may not work in older browsers.
const textToCopy = 'Hello, World!';
document.getElementById('copy-btn').addEventListener('click', function() {
  document.execCommand('copy', false, textToCopy);
});
  1. Using the setClipboardData() method: This method is supported in Internet Explorer.
const textToCopy = 'Hello, World!';
const textarea = document.getElementById('textarea');
textarea.value = textToCopy;
const textAreaData = textarea.getData('Text');
navigator.clipboard.setClipboardData(new ClipboardItem({ 'text/plain': textAreaData })).then(() => {
  console.log('Text written to clipboard');
});
  1. Using a library like clipboard: This library provides a simple way to copy text to the clipboard.
const clipboard = new ClipboardJS('copy-btn');
clipboard.on('success', function(e) {
  console.log('Text written to clipboard');
});

Latest blog posts

Explore the world of programming and cybersecurity through our curated collection of blog posts. From cutting-edge coding trends to the latest cyber threats and defense strategies, we've got you covered.