How to copy to clipboard using JavaScript

It is amazing how modern browsers had evolved, and how powerful they became we got to a point where we don’t need flash anymore.
A time ago the only way to copy to browser’s clipboard was from a button in the app using Flash, but with modern browsers we can achieve copy to clipboard using javascript, without using any plugin. First, let’s set the ground of what the clipboard is…

copy to clipboard using JavaScript

The clipboard is basically a place for storing and retrieving a single piece of cloned data, by data means from a simple string to a whole directory. There can be more than one clipboard present, for example, the “operative system clipboard”, it would be less difficult if all the applications were able/created to use the operative system clipboard, but unfortunately this is not always the case. For example, virtual machines, unless you explicitly turn on a clipboard integration option.
Following the same behavior are the web apps. Web applications runs in a sandbox environment, it restricts access to file system and the system clipboard, for security reasons. This article expose why the system clipboard is a restricted resource.
Fortunately, there ways to bypass those restrictions and gain access to system clipboard using JavaScript. This is post is about show several ways to do it.

Copy to clipboard using JavaScript

Example 1 (vanilla JavaScript):

This solution is a simple one but has some drawback because you must add an <input> or <textarea> element with the text to be copied to the DOM. The command used ‘execCommand’ allows us to execute other commands like cut, copy or paste.

The input or textarea to receive text you want to copy:

 
<input name="exampleClipboard" placeholder="Insert the text you want to copy" value="Example text" tabindex="1" autocomplete="off" maxlength="240" style="width:200px" type="text">
<p>
  <button id="copy">
    Copy text
  </button>
</p>
<p>
Right click paste or Ctr + v after click Copytext button <br/>
<textarea></textarea>
</p>

The function to call:

 

<script>
function copyToClipboard() {
document.querySelector('input').select();
document.execCommand('copy');}
</script>

The button:

 
<button id="howToCopyClipboard" onclick="copyToClipboard()">Copy</button

*You can change the input label for a textarea if you want. Keep in mind that this solution forces you to keep a maybe non desire input or textarea element in your page.

 
Try yourself

Example 2 (vanilla JavaScript):

This is a more elaborated solution where we validate compatibility with browsers. For this solution lets create a function that copies a string to the clipboard, this function must be called from within an event handler such as click. More reference to this method can be found here you can see a practical example here.

 

function copyToClipboard(text) {

if (window.clipboardData && window.clipboardData.setData) {
 // IE specific code path to prevent textarea being shown while dialog is visible.

return 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 MS 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 false;
        } finally {
            document.body.removeChild(textarea);
        }
    }
}

Example 3 (with a library): Clipboard js

It would be overwhelm to have to write validations for browser compatibility, etc, so Lets avoid reinvent the wheel and use a library that manages all this for you. ClipboardJs is very easy to use, here is an example:

 
<!-- Target -->

<input id="textToCopy" value="Any text you want to copy">

 

 

<!-- Trigger -->

<button class="btn" data-clipboard-target="#textToCopy">Copy to clipboard
</button>

Notice that

 data-clipboard-target 

do the job here. Let’s see another feature but this time is to cut instead of copy.
The only change needed is to add

 data-clipboard-action="cut"> 

like this:

  
<textarea id="textToCopy">Another feature … </textarea>
  
<!-- Trigger -->
<button class="btn" data-clipboard-action="cut" data-clipboard-target="#textToCopy">
    Cut to clipboard
</button>

More reference about this useful library can be found here.

Try yourself

At the end there isn’t universal solution to this task, out there are a lot of solutions in many different ways with just JavaScript (or JavaScript libraries without involving Flash), feel free to use the most suited for you.

One thought on “How to copy to clipboard using JavaScript

  1. Pingback: Albert

Leave a Reply

Your email address will not be published. Required fields are marked *