0

I am trying to implement the following two features:

  1. Users can copy the content in a textarea by clicking a button.
  2. I can know what content users copy (whether users copy with the button, Ctrl-C, or context menu) by listening to the copy event.

Here is my code (you can also see it in https://jsfiddle.net/hjtswedm/3/):

<html>

<head>
</head>
<script src='https://code.jquery.com/jquery-2.2.4.min.js'></script>
<script>
    $(window).bind("copy", function (e) {
        alert(document.getSelection().toString());
    });

    var copyText = function () {
        var txt = document.createElement("textarea");
        txt.textContent = $('#data').val();
        txt.style.position = "fixed";
        document.body.appendChild(txt);
        txt.select();
        try {
            return document.execCommand("copy");
        } catch (ex) {
            return false;
        } finally {
            document.body.removeChild(txt);
        }
    }
</script>

<body>
    Lorem Ipsum
    <textarea id="data">test copy</textarea>
    <button onclick="copyText()">
    Copy Text
    </button>
</body>

</html>

This code works fine with Chrome. However, with Firefox, Internet Explorer, and Edge, when I click the copy button, document.getSelection().toString() always returns empty strings. Is this by design, or did I miss something?

Thanks in advance.

LazarusX
  • 2,675
  • 2
  • 20
  • 30

1 Answers1

1

Working fiddle

Try :

 try {
    var range = document.createRange();
    range.selectNodeContents(txt);
    window.getSelection().addRange(range);
    return document.execCommand("copy");
  }
Shree
  • 18,997
  • 28
  • 86
  • 133
  • Thanks for answering. You fiddle works great for me too, but the code does not work if I save the code to an HTML file and open it in Microsoft Edge (still empty `document.getSelection().toString()`). Could you please help check again? Thanks. – LazarusX Jan 18 '17 at 03:15