Getting the Highlighted Text
Retrieving the highlighted text from a website's paragraph is a straightforward task that can be accomplished without additional libraries like jQuery.
Using Browser-Native Objects
The following code snippet demonstrates how to retrieve the highlighted text using browser-native objects:
function getSelectionText() { let text = ""; if (window.getSelection) { text = window.getSelection().toString(); } else if (document.selection && document.selection.type != "Control") { text = document.selection.createRange().text; } return text; }
Enhanced Implementation
To handle text selection in other form elements such as text areas and text input fields, an enhanced implementation could be used:
function getSelectionText() { let text = ""; const activeElement = document.activeElement; if ( (activeElement.tagName.toLowerCase() === "textarea") || (activeElement.tagName.toLowerCase() === "input" && /^(?:text|search|password|tel|url)$/i.test(activeElement.type)) && (typeof activeElement.selectionStart === "number") ) { text = activeElement.value.slice(activeElement.selectionStart, activeElement.selectionEnd); } else if (window.getSelection) { text = window.getSelection().toString(); } return text; }
Real-Time Update
To display the selected text in real time, event listeners can be added to document events like onmouseup, onkeyup, and onselectionchange. The updated text can then be populated into a designated element, such as a text box.
The above is the detailed content of How Can I Get Highlighted Text from a Website Using Only Browser-Native Objects?. For more information, please follow other related articles on the PHP Chinese website!