I am trying to implement the following two features:
- Users can copy the content in a
textarea
by clicking a button. - 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.