Skip to content

Instantly share code, notes, and snippets.

@UVLabs
Last active February 11, 2024 04:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save UVLabs/b678abb48fc368f5aa370a8820ff7ba4 to your computer and use it in GitHub Desktop.
Save UVLabs/b678abb48fc368f5aa370a8820ff7ba4 to your computer and use it in GitHub Desktop.
Detect highlighted text using JavaScript
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Selected Text Example</title>
<script>
// Adapted from: https://jsfiddle.net/timdown/SW54T/
// Fixed bug where alert would show twice: once when text is selected and again after page is cicked when exiting alert.
function getSelectedText() {
let text = "";
if (typeof window.getSelection !== "undefined") {
text = window.getSelection().toString();
} else if (typeof document.selection !== "undefined" && document.selection.type == "Text") {
text = document.selection.createRange().text;
}
return text;
}
function doSomethingWithSelectedText() {
let selectedText = getSelectedText();
if (selectedText) {
alert("Got selected text: " + selectedText);
document.getSelection().removeAllRanges(); // Deselect text after performing action
}
if(selectedText.includes('Example')){
window.location = 'https://example.com'
}
}
document.addEventListener("mouseup", doSomethingWithSelectedText);
document.addEventListener("keyup", doSomethingWithSelectedText);
</script>
</head>
<body>
<p>Highlight me</p>
<p>Double click me</p>
<p>Double Clicking/highlighting &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<strong>Example</strong>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;will redirect to example.com. Can also be used as a way to call an endpoint passing in the highlighted text. Be sure to sanitize.</p>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment