Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I check if the window of a process exists in applescript?

Tags:

applescript

I'm doing this:

tell application "System Events" to click button "Reply" of window 1 of process "Notification Center"

Which gets an exception if there's no window. So I tried this:

if exists (window 1 of process "Notification Center") then
    tell application "System Events" to click button "Reply" of window 1 of process "Notification Center"
end if 

But it seems like applescript doesn't do window 1 of process in a condition. How can I accomplish that?

like image 726
Kit Sunde Avatar asked Feb 11 '23 13:02

Kit Sunde


1 Answers

First, a simple test shows that AppleScript can do window 1 of process in a condition. I tested it using:

tell application "System Events"
    if exists (window 1 of process "Safari") then
        display dialog "Found window 1"
    end if
end tell

If there are any windows open in Safari, it will display the dialog window, otherwise it will not. So the issue lies elsewhere.

In fact, as I was typing this a notification came up letting me know that I can take a tour of “What’s New in OS X Yosemite”, so I took this as an opportunity and ran:

tell application "System Events"
    if exists (window 1 of process "Notification Center") then
        display dialog "Found window 1"
    end if
end tell

It did in fact display the dialog box; after I pressed Close on the notification, the same script did not detect a window and then display the dialog.

Here is a script that will create its own notification window and then attempt to detect it:

display notification "Hello"

--without a delay, this script will not immediately notice the window
delay 1

tell application "System Events"
    if exists (window 1 of process "Notification Center") then
        display dialog "Found window 1"
    end if
end tell

If you remove or comment out the delay 1 line, in my limited testing while writing this it will not detect that a window exists.

This leads me to suspect that the process you’re attempting to talk to is not Notification Center, or, perhaps more likely, that you’re attempting to talk to it too quickly.

If you are creating the notification yourself, or you are responding to it immediately after it is displayed, you may need a delay in order to detect it. (If the time between expecting the notification window to appear and it actually appearing is indeterminate, you may need to put the delay and the conditional into a loop.)

When you say that “AppleScript doesn’t do”, what do you mean? Does it give an error on that line, or does it simply not detect the window?

like image 181
Jerry Stratton Avatar answered Apr 27 '23 09:04

Jerry Stratton