Last active
February 11, 2024 04:28
-
-
Save UVLabs/b678abb48fc368f5aa370a8820ff7ba4 to your computer and use it in GitHub Desktop.
Detect highlighted text using JavaScript
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!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 <strong>Example</strong> 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