How might I run code(for example display dialog("test")
) using AppleScript only if the "Finder" Application is currently in focus/active.
Asked
Active
Viewed 2.3k times
1 Answers
26
This will work if the script is called from Script Editor, as it 'gets out of the way' to check the next app in line, but will fail if double clicked from Finder, as Finder will then always be last in line.
tell application "System Events"
set frontmostProcess to first process where it is frontmost
set visible of frontmostProcess to false
repeat while (frontmostProcess is frontmost)
delay 0.2
end repeat
set secondFrontmost to name of first process where it is frontmost
set frontmost of frontmostProcess to true
end tell
tell application (path to frontmost application as text)
if "Finder" is in secondFrontmost then
display dialog ("Finder was last in front")
else
display dialog (secondFrontmost & " was last in front")
end if
end tell
Leaving previous answer here for posterity
Rejigged entire answer after having not read the question properly initially ;-)
tell application "System Events"
set activeApp to name of first application process whose frontmost is true
if "Finder" is in activeApp then
display dialog ("test")
else
display dialog ("test2")
end if
end tell

Tetsujin
- 115,663
-
+1 Although your proposed solution doesn't seem to work as is. I get "test" as long as the application is open and not necessarily if it is active or not. – William Feb 13 '15 at 09:31
-
-
complete rewrite, now I'm back at my desktop - this now does exactly what you asked. – Tetsujin Feb 15 '15 at 12:29
-
Hmm.. If I add the applescript as an app to to the dock it only displays "test2" no matter what application I have originally focused. – William Feb 15 '15 at 14:08
-
probably because the Applescript app is frontmost. Test by adding a 3s delay, then clicking the desktop between launch & trigger [that's how I tested it here] – Tetsujin Feb 15 '15 at 15:05
-
2you can also replace the second dialog command with
display dialog (activeApp)
to confirm exactly what the script thinks is the frontmost. – Kent Feb 16 '15 at 04:35 -
1Be careful with this -- some apps's app names (e.g.,
tell application "app_name"
) differ from their process names (e.g.,set frontmost of process "app_process" to true
). – BallpointBen Jul 24 '18 at 04:51 -
Also, be careful if you have different versions of the same app installed (e.g. Firefox)! It may (probably will) launch the wrong one. – SilverWolf Oct 21 '18 at 21:49
-
key code (insert code here)
works but you can't know ahead of time what application is focused. – William Feb 16 '15 at 19:32