Quick Tip: Accessing The Clipboard With JavaScript

In this article we’re going to show you how to use simple vanilla JavaScript snippets to:

  1. Add text to the clipboard on user action, such as the press of a button.
  2. Modify the content of the clipboard when a user copies something.

The APIs we will be using don’t require any external libraries, and have almost perfect browser compatibility!

.. To make this happen we will need to use a cool JavaScript method called <a href="https://developer.mozilla.org/en-US/docs/Web/API/Document/execCommand" target="_blank">execCommand()</a>. It allows us to invoke a number of different events that manipulate editable content such as making text bold/italic, doing undo/redo, and also copy/cut/paste.

<span class="hljs-built_in">document</span>.execCommand(<span class="hljs-string">'copy'</span>);