@xidiot I recently discovered a method that (sometimes) works better or faster in certain apps than determining the text fields. You probably already know this , so just a quick note.
Sometimes it is enough to determine whether the cursor is in a text field or not, the name doesn't matter. If so I look for a menu item that is not active when the cursor is not in a text field. For example, “paste”. This can be used to create a condition that works very reliably for me. Andreas has written a script for this. Very useful