Welcome to 16892 Developer Community-Open, Learning,Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

The coder's fantasy

I created a simple user script to act very quickly on the text I selected. It goes like this:

  1. I select a word, a website (doesn't have to be a link), or a phrase from, let's say, a p element
  2. When I press the trigger key, the algorithm will try to figure out if it's a website or text. It will open a tab: if it's a website, that's what it'll load; if it's text, it will google it.

The problem shows its ugly head

It works great except when I'm editing text. If I'm editing something I've written in a textarea/input it will fire, potentially losing what I wrote. Fortunately, there's usually cache, or even the site will warn me for having unsaved changes, which saves me from losing whatever I wrote. But it's something to fix.

The challenge

The userscript should only run on text that can't be edited. You'd think it is as easy as not calling the function if the selected text is within a textarea. But there are many ways to display editable content without using classical elements. The "best" filter I've found is to check for document.activeElement.isContentEditable. However, in this very box, that returns false. This is a textarea element, so I can add it to the filter, and I can do so with a few more I can think of. But apart from being an ugly solution, it is not foolproof.

Besides adding a "did you run me by accident?" prompt, is there a better way to do this?

Edit: my current code


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
453 views
Welcome To Ask or Share your Answers For Others

1 Answer

If I understand correctly .... here is an example of how to go about it.

if (['TEXTAREA', 'INPUT'].includes(document.activeElement.nodeName)) {
  // it is in textarea, input
}
else if (document.activeElement.isContentEditable) {
  // it is in contentEditable element
}
else {
  // not above
}

Above is not the only method, e.g. the following using window.getSelection():

const sel = window.getSelection();
const text = sel.toString();

if (!text.trim()) {
  // there is no selection
  // or selection is white-space
  // or selection is in textarea, input
}
else if (document.activeElement.isContentEditable) {
  // it is in contentEditable element
}
else {
  // not above
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to 16892 Developer Community-Open, Learning and Share
...