Languages
[Edit]
EN

JavaScript - how to copy text to system clipboard?

15 points
Created by:
chelsea
326

In this article, we would like to show how to copy some text into the system clipboard in JavaScript.

Quick solution:

navigator.clipboard.writeText('Hello Dirask!'); // WORKS ONLY IN MODERN BROWSERS !!!

// go to the next section to custom example to see the universal solution.

 

The article shows to approaches:

  1. with a custom class that uses some trick to copy text into the system clipboard,
  2. with modern JavaScript API - that approach can be not supported by some browsers.

1. Custom class that copy text to the system clipboard

The example presented in this section is universal and works in each browser. To understand how class works read the note below example.

// ONLINE-RUNNER:browser;

<!doctype html>
<html>
  <head>
    <script>

      window.Clipboard = new function() {
          var transit = null;
          var element = null;
          function copy(text) {
              element.value = text;
              element.style.display = 'block';
              element.select();
              document.execCommand('copy');
              element.style.display = 'none';
          }
          window.addEventListener('load', function() {
              element = document.createElement('textarea');
              element.setAttribute('style', 'border: none; width: 0; height: 0; display: none');
              document.body.appendChild(element);
              if (transit) {
                  copy(transit);
              }
          });
          this.copy = function(text) {
              if (element) {
                  if (element.parentNode == null) {
                        throw new Error('Element has not been removed from document.');
                  }
                  copy(text);
              } else {
                  transit = text;
              }
          };
      };

      // Usage example:
      //
      //     Clipboard.copy('Hello Dirask!')

    </script>
  </head>
  <body>
    <div>
      <span>Copy to clipboard:</span>
<!--
      Usage example:
-->
      <button onclick="Clipboard.copy('Hello Dirask!')">Hello Dirask!</button>
      <button onclick="Clipboard.copy('My name is John')">My name is John</button>
    </div>
    <textarea style="padding: 20px; width: 300px;" 
              placeholder="You can paste content of your clipboard here :)"></textarea>
  </body>
</html>

Explanation:

  • textarea supports multiline texts,
  • textarea element is set to 0x0 px to make it invisible for user during copy operation - to element prevent flickering on the web site,
  • to make text copy some simple tricks are necessary:
    • text should be put inside text field,
    • it is possible to make text copy only if text field is visible - because of security reasons - this is why element visibility is changed to visible during the operation,
    • to make copy it is necessary to select copied text before the operation
  • copy operation is realised by copy command.

Note: after click on the buttons you can paste text to some plase.

2. navigator.clipboard object example

This API has working draft status and is not supported by all web browsers.

More information about the API is available here.

// ONLINE-RUNNER:browser;

<!doctype html>
<html>
  <body>
    <div>
      <span>Copy to clipboard:</span>
<!--
      Usage example:
-->
      <button onclick="navigator.clipboard.writeText('Hello Dirask!')">
        Hello Dirask!
      </button>
      <button onclick="navigator.clipboard.writeText('My name is John')">
        My name is John
      </button>
    </div>
    <textarea style="padding: 20px; width: 300px;" 
              placeholder="You can paste content of your clipboard here :)"></textarea>
  </body>
</html>
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join