How Do I Run Script on Selected File in File Open Dialog?
I would like to run an AppleScript when the File > Open Dialog is open.
My immediate use case is with Visual Studio Code (VSC), when I want to open a script file. But the script file must first be converted to a text file with a ".jxa" extension.
Just a partial potential tip here… It’s long been a built-in Mac feature of Open/Save dialogs whereby the Command-R shortcut reveals the selected file in the Finder. Assuming Default Folder retains that capability in some way, maybe that gets you closer to acting on the selected file.
While there is an accessibility property for the file-url you can't get its value with AppleScript.
AppleScript just beeps irritatingly at you and throws this error:
System Events got an error: AppleEvent handler failed.
Num: -10000
If you look at the file object in the open dialog with UI Browser or the Accessibility Inspector you'll see this junk:
AXURL file:///.file/id=6571367.12732750
So our caustic friend's idea is probably the most viable one for normal users.
For more advanced users:
You can get the file name, and if it's unique enough you could find it quickly by scripting Spotlight.
tell application "System Events"
tell application process "Safari"
tell window "Open"
tell group 1
tell splitter group 1
tell splitter group 1
tell scroll area 1
tell outline 1
tell row 4
tell UI element 1
tell text field 1
set fileName to attribute "AXFileName"'s value
end tell
end tell
end tell
end tell
end tell
end tell
end tell
end tell
end tell
end tell
end tell
set shCMD to "mdfind 'kMDItemFSName == \"" & fileName & "\"'"
set filePath to do shell script shCMD
Also – since you have Default Folder – you can find the current location of the dialog with AppleScript.
Unfortunately the only utility I know of that offers the ability is Default Folder.
So – file name plus container folder gets you a path.
Here are some hints for working with Default Folder:
My thanks to both @NaOH and @ccstone for your suggestions and comments.
Perfect. I put this in the below macro, and it opens the new JXA text file very fast.
Sorry, I'm just posting the macro image for now to show the process. The script has a couple of calls to my Script Lib that I will need to replace before posting the macro file and script text.