How to programmatically copy to the clipboard in JavaScript?

Vajid KagdiVajid Kagdi
2 min read
  1. Async Clipboard API - navigator.clipboard.writeText

    • Text-focused portion available in Chrome 66 (Since March 2018)
    • Access is asynchronous and uses JavaScript Promises, can be written so security user prompts (if displayed) don't interrupt the JavaScript in the page.
    • Text can be copied to the clipboard directly from a variable.
    • Only supported on pages served over HTTPS.
    • In Chrome 66 pages inactive tabs can write to the clipboard without a permissions prompt.
    var text = "Example text to appear on clipboard";
    navigator.clipboard.writeText(text).then(function() {
     console.log('Async: Copying to clipboard was successful!');
    }, function(err) {
     console.error('Async: Could not copy text: ', err);
    });
    
  2. document.execCommand('copy')

    Note: You will not see the textarea, as it is added and removed within the same synchronous invocation of Javascript code.

  // Copies a string to the clipboard. Must be called from within an
  // event handler such as click. May return false if it failed, but
  // this is not always possible. Browser support for Chrome 43+,
  // Firefox 42+, Safari 10+, Edge and Internet Explorer 10+.
  // Internet Explorer: The clipboard feature may be disabled by
  // an administrator. By default a prompt is shown the first
  // time the clipboard is used (per session).
  function copyToClipboard(text) {
      if (window.clipboardData && window.clipboardData.setData) {
          // Internet Explorer-specific code path to prevent textarea being shown while dialog is visible.
          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";  // Prevent scrolling to bottom of page in Microsoft Edge.
          document.body.appendChild(textarea);
          textarea.select();
          try {
              return document.execCommand("copy");  // Security exception may be thrown by some browsers.
          }
          catch (ex) {
              console.warn("Copy to clipboard failed.", ex);
              return prompt("Copy to clipboard: Ctrl+C, Enter", text);
          }
          finally {
              document.body.removeChild(textarea);
          }
      }
  }

Some things to watch out for if you are implementing this yourself:

  1. For security reasons, this can only called from an event handler such as click (Just as with opening windows).
  2. Internet Explorer will show a permission dialog the first time the clipboard is updated.
  3. Internet Explorer, and Edge will scroll when the textarea is focused.
  4. execCommand() may throw error in some cases.
  5. Newlines and tabs can get swallowed unless you use a textarea.
  6. The textarea will be visible while the Internet Explorer dialog is shown, you either need to hide it, or use the Internet Explorer specific clipboardData API.
  7. In Internet Explorer system administrators can disable the clipboard API.
0
Subscribe to my newsletter

Read articles from Vajid Kagdi directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Vajid Kagdi
Vajid Kagdi

Graduated with a Master’s degree in Software Engineering from San Jose State University in December 2019 and currently working at PayPal on the Customer Journey Platform. I enjoy generating new ideas and devising feasible solutions to broadly relevant problems. My colleagues would describe me as a driven, resourceful individual who maintains a positive, proactive attitude when faced with adversity. Interested to work in areas related to Distributed Systems, Cloud Infrastructure and Micro-Services. I get a lot of satisfaction from the constant learning and puzzle solving that comes with my profession and contributing to a successful and worthwhile product. My expertise includes project design and management, data analysis and interpretation, and the development and implementation of software products.