Very basic AppleScript to open file and go to page (text field issue)

I am a complete beginner to Mac scripting.
To learn GUI scripting, I set the following goal for myself : have an Applescript emulate what happens
when a file is opened in Preview, the “Go to Page …” menu item is clicked and the user goes to page 3.

Here is my failed attempt :


tell application "Preview" to open "some:path:my_file.pdf"


tell application "System Events"
	tell process "Preview"
		set frontmost to true
		click menu item "Go to Page…" of menu "Go" of menu bar 1
		set value of text field 1 of window 1 to "3"
		tell application "System Events"
			key code 36
		end tell
	end tell
end tell

and here is the error message I get :

error “System Events got an error: Can’t get text field 1 of window 1 of process "Preview". Invalid index.” number -1719 from text field 1 of window 1 of process “Preview”

Model: MacBook Air
AppleScript: 2.7
Browser: Safari 605.1.15
Operating System: macOS 10.14

cocoa_on_apple. I have made three changes to your script, after which it ran as expected on my Catalina computer.

  • Added “file” in line 1 of the script. Without this change, an error occurs under Catalina.

  • Added “of sheet 1” midpoint in the script. This is the reason for the error you received.

  • Removed a redundant System Events tell statement.

tell application "Preview" to open file "some:path:my_file.pdf"

tell application "System Events"
	tell process "Preview"
		set frontmost to true
		click menu item "Go to Page…" of menu "Go" of menu bar 1
		set value of text field 1 of sheet 1 of window 1 to "3"
	end tell
	key code 36
end tell

Works for me too, thanks a lot peavine.