This AppleScript (courtesy of Nige_S) will get you pretty far:
tell application "Finder"
if front window exists then
tell application "System Events"
tell process "Finder"
if enabled of menu item "Close Window" of menu "File" of menu bar 1 then
display dialog "Window is active"
else
display dialog "Desktop is active, window(s) open"
end if
end tell
end tell
else
display dialog "Desktop only"
end if
end tell
Change those display dialog
commands to return
, and use the variable for your conditional.
The challenge here is getting the Trigger right.
- "When Finder Activates" doesn't work if you click the Desktop while already in a Finder window.
- "When Focused Window Title Changes" mostly works, but shows curious behavior when clicking on the Desktop then another Finder window: it somehow triggers twice.
I haven't been able to debug the title change double trigger, but even if you got that to work that trigger would be very frequent, which may be inadvisable.