AppleScript get active Application How might I run code(for example display dialog("test")) using AppleScript only if the "Finder" Application is currently in focus/active.
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 &amp; " 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