Apple Script – How to check if a window with a specific title exists

applescriptautomatorcatalina

I would like to create an apple script that checks if a window of an application with a specific name (not id or index) exists. I used the following code in a previous script, and it works:

tell application "Notes" to close (every window whose name is "Notes")

However, I can't figure out how to check if a window with this title exists. This should be incredibly simple. How do I do it?

Best Answer

You can do this with the System Events application - for example:

tell application "System Events"
    if exists (window "Terminal — -zsh" of process "Terminal") then
        display dialog "Found"
    else
        display dialog "Not found"
    end if
end tell

Note that process is case sensitive while window is not. Therefore this will work

if exists (window "TeRmInAl — -ZsH" of process "Terminal")

but this will not

if exists (window "Terminal — -zsh" of process "terminal")

Script Editor

If you are running from Script Editor you must authorise it in System Preferences > Security & Privacy > Privacy > Accessibility

Accessibility