AppleScript/Unix: How to get the current MacOS foreground application name

AppleScript foreground application FAQ: How can I get the name of the current MacOS foreground application in AppleScript?

AppleScript foreground application script

This may be the craziest thing I’ve done with AppleScript yet, but in short, I’m trying to see if I can get the name of the foreground application on my MacOS system at any moment. For crazy reasons, I’m doing this from the Mac Terminal (the Unix system on MacOS), and it appears to be working, so what I’m really doing is (a) running an AppleScript script from Unix, (b) getting the name of the foreground Mac application, and (c) returning that name back to my Unix shell script from my AppleScript script.

Here’s how I’ve run this AppleScript command from the Mac Unix command line:

$ osascript -e 'tell application "System Events"' -e 'set frontApp to name of first application process whose frontmost is true' -e 'end tell'

Terminal

(Many thanks to someone on stackoverflow for this particular nugget of code.)

Of course if you just run this AppleScript command from your Mac Unix command line, the answer is always going to be “Terminal,” but, if you run it from crontab, or perhaps from a timed delay in a Java application, then you should get a different answer.

To demonstrate that this does work, I just ran this command, preceded by a Unix sleep command, like this:

$ sleep 5; osascript -e 'tell application "System Events"' -e 'set frontApp to name of first application process whose frontmost is true' -e 'end tell'

then switched over to my Firefox browser for a few moments. When I switched back to my Mac Terminal, I saw this result:

firefox-bin

As you can see, this does indeed work.

AppleScript from Unix or Java

As you can see, you use the osascript command to run AppleScript commands from the Mac OS X Unix command line, as I’ve shown previously with my How to run AppleScript commands from Java tutorial.

This probably isn’t going to work for the crazy thing I’m trying to do today, but again, if you run it from something like crontab, or from a Java application with a time delay, I think you will be able to get the name of the current MacOS foreground application. Either way, in case you ever need to run an AppleScript command from the Unix shell, or from a Java application, this demonstrates another AppleScript/Unix example.