Search code examples
macosapplescript

how to make the element selection to return null instead of throw error in applescript


I am debugging a legacy desktop automation tool which use AppleScript for UI control on MacOS. One of the script keeps failing with error "System Events got an error: Can’t get static text \"2\" of window \"UISoup – mac_utils.py\" of application process \"pycharm\"." number -1728 from static text "2" of window "UISoup – mac_utils.py" of application process "pycharm", and here is the script

tell application "System Events" to tell process "PyCharm"
    set visible to true
    set uiElement to static text "2" of window "UISoup – mac_utils.py" of application process "pycharm" of application "System Events"
    set layer to 1
    if uiElement = null then
        set layer to 0
        set collectedElements to {UI elements of front window, layer}
    else
        set layer to layer + 1
        set collectedElements to {null, layer}
        if name of attributes of uiElement contains "AXChildren" then
            set collectedElements to {value of attribute "AXChildren" of uiElement, layer}
        end if
    end if
end tell

It seems like this line set uiElement to static text "2" of window "UISoup – mac_utils.py" of application process "pycharm" of application "System Events" should set the uiElement to null if the element is not found. But in fact it will throw error instead. How to let it return null instead of throw error to make it works? Thank you.


Solution

  • In the AppleScript equivalent of null is missing value. When GUI scripting, the process should be frontmost. You can check existing of UI elements using command exists (you can use try block as well).

    tell application "System Events" to tell process "PyCharm"
        set frontmost to true
        -- set visible to true
        set uiElementExists to exists static text "2" of window "UISoup – mac_utils.py"
        set layer to 1
        if not uiElementExists then
            set layer to 0
            set collectedElements to {UI elements of front window, layer}
        else
            set layer to layer + 1
            set collectedElements to {missing value, layer}
            set uiElement to static text "2" of window "UISoup – mac_utils.py"
            if name of attributes of uiElement contains "AXChildren" then
                set collectedElements to {value of attribute "AXChildren" of uiElement, layer}
            end if
        end if
    end tell