Home > Web Front-end > JS Tutorial > How Can I Get Highlighted Text from a Website Using Only Browser-Native Objects?

How Can I Get Highlighted Text from a Website Using Only Browser-Native Objects?

Susan Sarandon
Release: 2024-12-15 20:05:18
Original
945 people have browsed it

How Can I Get Highlighted Text from a Website Using Only Browser-Native Objects?

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;
}
Copy after login

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;
}
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template