How to get name of frontmost app with AppleScript and use it to get the filepath

patrick picture patrick · Jul 12, 2013 · Viewed 17.9k times · Source

What I try to do:

When I'm in one of my text editors (TextEdit, Byword, FoldingText) I want this AppleScript to display the file path.

I figured asking for the frontmost window app get's me the apps name nice and easily and then I can ask for the POSIX path in the next step.

The Problem:

The script is already 99% there, but I'm missing something. When I try to use the variable of activeApp it doesn't work and I get this error:

Error Number:System Events got an error: Can’t get application {"TextEdit"}.
-1728

Here's the script:

tell application "System Events"
     set activeApp to name of application processes whose frontmost is true

     --This doesn't work either:
     --do shell script "php -r 'echo urldecode(\"" & activeApp & "\");'"

     tell application activeApp
         set myPath to POSIX path of (get file of front document)
     end tell
     display dialog myPath
end tell

If I exchange activeApp with "TextEdit" everything works. Help would be appreciated.

Maybe there's something in here that helps: Get process name from application name and vice versa, using Applescript

Answer

Lri picture Lri · Jul 12, 2013

Either get the path property of a document or use System Events to get value of attribute "AXDocument":

try
    tell application (path to frontmost application as text)
        (path of document 1) as text
    end tell
on error
    try
        tell application "System Events" to tell (process 1 where frontmost is true)
            value of attribute "AXDocument" of window 1
        end tell
        do shell script "x=" & quoted form of result & "
        x=${x/#file:\\/\\/}
        x=${x/#localhost} # 10.8 and earlier
        printf ${x//%/\\\\x}"
    end try
end try

The first method didn't work with Preview, TextMate 2, Sublime Text, or iChm, and the second method didn't work with Acorn. The second method requires access for assistive devices to be enabled.