Text Selection Copier
Interact with user selections. Use the `window.getSelection()` API to retrieve exactly what text the user has highlighted on your page.
Highlight any part of this sentence with your mouse cursor. Then click the button below to extract it.
Selected:
Copy the Script
<script>
function getSelectedText() {
var text = "";
if (window.getSelection) {
text = window.getSelection().toString();
} else if (document.selection && document.selection.type != "Control") {
text = document.selection.createRange().text; // IE8 support
}
return text;
}
function showSelection() {
alert("You selected: " + getSelectedText());
}
</script>
<button onmousedown="showSelection()">What did I select?</button>
Frequently Asked Questions
Browsers often block automatic copying to the clipboard (`execCommand('copy')`) unless triggered by a direct user click event. This script gets the text; putting it in the clipboard usually requires a button click.
Yes. You can use the Selection API to get the range and wrap the selected text in a `` tag.
Yes. The Selection API works on mobile when users tap and hold to select text.