How to detect if the focus element is a text field?

Hi All,

I'm trying to do some things when the focus is not in a text field, especially for Chrome. This feature came within the former Karabiner but didn't work since macOS 10.12. So I want to work around with KM. Currently I only have an idea which runs JavaScript in Chrome, but it's a little bit slow.

I did some Googling but no luck. Only find out a similar suggestion thread:

Is it possible to do this with KM built-in actions and AppleScript or even python?

I don’t know of any way to do this in general. If it is in a Chrome window, then you could probably use Execute JavaScript in Google Chrome action, and ask the JavaScript where the text focus is, but I don’t know how to do the latter in JavaScript.

Otherwise, unless there is some sort of special AppleScript support, you cannot generally find where the text focus is.

See javascript - How do I find out which DOM element has the focus? - Stack Overflow

postAuthor: JW.
postDate: 2009-01-30
postURL: javascript - How do I find out which DOM element has the focus? - Stack Overflow
NoteTitle: How do I find out which DOM element has the focus?


> Use
 `document.activeElement`

> it is supported in all major browsers.

> Previously, if you were trying to find out what form field has focus, you could not. To emulate detection within older browsers, add a "focus" event handler to all fields and record the last-focused field in a variable. Add a "blur" handler to clear the variable upon a blur event for the last-focused field.

> Related links:

> activeElement Browser Compatibility
> jQuery alternative for document.activeElement

@peternlewis @JMichaelTX
Thanks. I’ve already tried document.activeElement.nodeName, but it’s not fast enough. It seems that Chrome needs some time to load the DOM. Perhaps I could only wait for Karabiner-Elements.