How do I copy to the clipboard in JavaScript?


What is the best way to copy text to the clipboard? (multi-browser)

I have tried:

function copyToClipboard(text) {
    if (window.clipboardData) { // Internet Explorer
        window.clipboardData.setData("Text", text);
    } else { "UniversalXPConnect");  
        const clipboardHelper = Components.classes[";1"].getService(Components.interfaces.nsIClipboardHelper);  

but in Internet Explorer it gives a syntax error. In Firefox, it says unsafeWindow is not defined.

A nice trick without flash: How does Trello access the user's clipboard?

12/3/2017 3:44:16 PM

Automatic copying to clipboard may be dangerous, therefore most browsers (except IE) make it very difficult. Personally, I use the following simple trick:

function copyToClipboard(text) {
  window.prompt("Copy to clipboard: Ctrl+C, Enter", text);

The user is presented with the prompt box, where the text to be copied is already selected. Now it's enough to press Ctrl+C and Enter (to close the box) -- and voila!

Now the clipboard copy operation is SAFE, because the user does it manually (but in a pretty straightforward way). Of course, works in all browsers.

<button id="demo" onclick="copyToClipboard(document.getElementById('demo').innerHTML)">This is what I want to copy</button>

  function copyToClipboard(text) {
    window.prompt("Copy to clipboard: Ctrl+C, Enter", text);


The following approach works in Chrome, Firefox, Internet Explorer and Edge, and in recent versions of Safari (copy support was added in version 10 which was released Oct 2016).

  • Create a textarea and set its contents to the text you want copied to the clipboard.
  • Append the textarea to the DOM.
  • Select the text in the textarea.
  • Call document.execCommand("copy")
  • Remove the textarea from the dom.

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

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

  • For security reasons, this can only called from an event handler such as click (Just as with opening windows).
  • Internet Explorer will show a permission dialog the first time the clipboard is updated.
  • Internet Explorer, and Edge will scroll when the textarea is focused.
  • execCommand() may throw in some cases.
  • Newlines and tabs can get swallowed unless you use a textarea. (Most articles seem to recommend using a div)
  • 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.
  • In Internet Explorer system administrators can disable the clipboard API.

The function below should handle all of the following issues as cleanly as possible. Please leave a comment if you find any problems or have any suggestions for improving it.

// 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 clipboardData.setData("Text", text);

    else if (document.queryCommandSupported && document.queryCommandSupported("copy")) {
        var textarea = document.createElement("textarea");
        textarea.textContent = text; = "fixed";  // Prevent scrolling to bottom of page in Microsoft Edge.
        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 {


Here is my take on that one...

function copy(text) {
    var input = document.createElement('input');
    input.setAttribute('value', text);
    var result = document.execCommand('copy');
    return result;

@korayem: Note that using html input field won't respect line breaks \n and will flatten any text into a single line.

As mentioned by @nikksan in the comments, using textarea will fix the problem as follows:

function copy(text) {
    var input = document.createElement('textarea');
    input.innerHTML = text;
    var result = document.execCommand('copy');
    return result;

Reading and modifying the clipboard from a webpage raises security and privacy concerns. However, in Internet Explorer, it is possible to do it. I found this example snippet:

    <script type="text/javascript">
        function select_all(obj) {
            var text_val=eval(obj);
            r = text_val.createTextRange();
            if (!r.execCommand) return; // feature detection
    <input value=""
     onclick="select_all(this)" name="url" type="text" />


If you want a really simple solution (takes less than 5 minutes to integrate) and looks good right out of the box, then Clippy is a nice alternative to some of the more complex solutions.

It was written by a co-founder of GitHub. Example Flash embed code below:

  <param name="movie" value="/flash/clippy.swf"/>
  <param name="allowScriptAccess" value="always"/>
  <param name="quality" value="high"/>
  <param name="scale" value="noscale"/>
  <param NAME="FlashVars" value="text=#{text}"/>
  <param name="bgcolor" value="#{bgcolor}"/>

Remember to replace #{text} with the text you need copied, and #{bgcolor} with a color.


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Email: [email protected]