Applescript – wait for window/dialog to appear/disappear

applescriptdialog

I am scripting iTunes and have bumped into two problems when I in one step of my script need to verify wether windows/dialogs are displayed or not.

  1. According to Waiting until a window exists in Applescript? this should be valid code

    repeat until window "Print" of process "Evernote" exists

but when I compile it I get this error message "Expected end of line but found “"” (" refers to the " before E in Evernote). Why? That question is 2,5 years old, has anything changed since then? I am running OS X 10.11.

  1. I can use this code to verify wether the song info-window is open in iTunes

    repeat until (not (exists window "Song Info"))

but when I try to look for en Open dialog with a similar line

repeat until (exists window "Open")

the window is not detected. I have used Accessibility Inspector to get some properties of the Song Info window and the Open dialog and the only differences I have noticed is the name as well as the type. Song Info is a "window" while Open is a "dialog". Hence, I also tried these two variations on the previous code:

repeat until (exists dialog "Open")
repeat until (exists window dialog "Open")
repeat until (exists dialog window "Open")

but none of them compile.

How do I detect the Open dialog?

Best Answer

The reason you're getting "Syntax Error Expected end of line but found “"”." when using repeat until window "Print" of process "Evernote" exists is because you're using it out of context of the calling application. You might say meaning, within the context of the calling application, it doesn't understand the command and the AppleScript Editor is not that well written to express what the error really means.

Anyway, the example code below when run in ScriptEditor, by itself, will wait to display the "Your wait is over!" dialog box until iTunes is open and you press O or click File > Add to Library… on the iTunes menu.

tell current application
    tell application "System Events"
        repeat until (exists window "Add To Library" of application process "iTunes")
            delay 1
        end repeat
    end tell
    activate
    display dialog "Your wait is over!"
end tell
  • Note the use of the delay command within the repeat loop. Obviously the value can be set to something else, even fractions of a second, however you should alway use a delay to avoid System Events from needlessly triggering the loop hundreds of time a second until the condition is meet.

As a general rule I've found that anytime I'm using code that has ... process ... or ... application process ... it's a call being made to or by System Events and as such in this use case, the repeat loop has to be within a tell statement or block of System Events in order to not get the error mentioned in your OP.