3 Ways to Copy to the Clipboard in JavaScript

Marika Lam
2 min readSep 12, 2022

1. Async Clipboard API

[navigator.clipboard.writeText]
  • Text-focused portion available in Chrome 66 (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') (deprecated) 👎

  • Most browsers support this as of ~April 2015 (see Browser Support below).
  • Access is synchronous, i.e. stops JavaScript in the page until complete including displaying and user interacting with any security prompts.
  • Text is read from the DOM and placed on the clipboard.
  • During testing ~April 2015 only Internet Explorer was noted as displaying permissions prompts whilst writing to the clipboard.

--

--