Getting the currently open file and path from Preview

So, I know that Preview isn’t technically scriptable through applescript except for some hacks using UI scripting, but I was wondering if there was any way to get the filename and path of the active window in Preview.

I just want the name of the file so I can easily pass it to a shell script, but I want to be able to just run the script from preview without having to input it manually. Is there any way to do this. It doesn’t have to be elegant.

Hi,

you can do it with GUI scripting, try this


activate application "Preview"
tell application "System Events"
	tell process "Preview"
		tell (1st window whose value of attribute "AXMain" is true)
			set fileURL to value of attribute "AXDocument"
			set windowTitle to value of attribute "AXTitle"
		end tell
	end tell
end tell

Stefan’s script is very useful, inasmuch as it can get the path of the file of multiple applications’ windows. The following variant can be run in the background, using Script Menu:

tell application “System Events” to tell item 1 of (processes whose frontmost is true)
tell (1st window whose value of attribute “AXMain” is true)
set fileURL to value of attribute “AXDocument”
set windowTitle to value of attribute “AXTitle”
display dialog fileURL
end tell --first window
end tell --front process

Jonathan

Operating System: Mac OS X (10.8)