System Events work fine in debug, but are skipped on running the app

A strange one.

When I open a page in chrome via applescript and subsequently save the page while in debug, this works fine.

However, when running the saved app, the save dialog comes up, but the page is never or intermittently saved. How can I make sure the ‘keystroke enter’ line is executed?


tell application "System Events"
	
	keystroke "s" using command down
	delay 2
	keystroke return
	delay 2
	
end tell

You might have a little more success using UI elements rather than relying on keystrokes.

The repeat loop while waiting for the sheet is a little trick I use frequently to minimize delays in script execution and gracefully give up if something unexpected happens.


tell application "System Events" to tell application process "Google Chrome"
	
	click menu item "Save Page As." of menu 1 of menu bar item "File" of menu bar 1
		
	-- Wait for the sheet to appear, keep trying if it isn't there yet
	repeat 10 times
		try
			click button "Save" of sheet 1 of window 1
			exit repeat
		on error
			delay 1
		end try
	end repeat
	
end tell

This edited version behaves flawlessly :


activate application "Google Chrome" # ADDED
tell application "System Events" to tell application process "Google Chrome" # EDITED
	
	keystroke "s" using command down
	delay 2
	keystroke return
	delay 2
	
end tell

KOENIG Yvan (VALLAURIS, France) samedi 27 avril 2013 11:14:13

It’s bringing Google Chrome to the front which does the trick. Keystrokes are delivered to the frontmost process, whatever that may happen to be. Explicitly telling a process to do keystrokes makes no difference.

tell application "TextEdit" to activate
tell application "System Events" to keystroke "TextEdit frontmost"

tell me to activate
tell application "System Events"
	tell application process "TextEdit"
		keystroke "Me frontmost"
	end tell
end tell