简体   繁体   中英

How to determine if user input is in a rich text editor (on all sites)

I'm working on a Chrome translation extension that allows users to select a text and press a key (T) to display the translation directly behind the text.

But if the user selects text and presses (T) in the input box, the extension will also show the translation result, which is not what I want. Fortunately, the input field is usually wrapped around the <input></input> tag, so I can tell that the user does not trigger the translation function when the <input> tag is used.

if (keyCode == "T") {
    let userSelection = window.getSelection();
    let userSelectionNode = window.getSelection().anchorNode.parentElement;
    if ($(userSelectionNode).find("input").length == 0) {
        let userSelection_string = userSelection.toString();
        if (userSelection_string.length > 0) {
            getTranslate(userSelection_string);
        }
    }
}

But if the user is in a rich text editor, my method doesn't work, and I can't tell if the user is in a rich text editor. So do I have a way to tell if the user is in a rich text editor? It is important to note that the extension runs on all web pages, so the method should be generic and not targeted at a particular rich text editor

They use contenteditable attribute, which you can detect easily:

let el = window.getSelection().anchorNode.parentElement;

if (!el.closest('[contenteditable="true"], [contenteditable=""], input, textarea')) {
  // not in a text input
  // .........
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM