Error when running AppleScript to close notifications [SOLVED]

I have this AppleScript to close all notification windows:

-- Define the content to search for in the notification
set targetNotificationContent to "Running Backup Recently Modified"

-- Define how long the notification is displayed before being closed
delay 2

-- Use System Events to interact with UI elements
tell application "System Events"
	-- Access the notifications UI element
	tell process "Notification Center"
		-- Loop through each window (each notification is a window)
		repeat with notif in windows
			-- Check if the notification contains the target content
			if (value of static text 1 of notif contains targetNotificationContent) then
				-- Close the notification
				perform action "AXPress" of button 1 of notif
				exit repeat
			end if
		end repeat
	end tell
end tell

It works most of the time, but sometimes I get this error:

Execute an AppleScript failed with script error: text-script:563:588: execution error: System Events got an error: Can’t get item 2 of every window of process "Notification Center". Invalid index. (-1719)

I'm no expert in AppleScript. I believe I got this from ChatGPT or something, so maybe there's something that needs to be fixed. But again, it works 90% of the time.

EDIT: ChatGPT explained it to me and offered a solution.

The error occurs when the script tries to access static text 1 of notif, but the window doesn't have any static text elements, or fewer than expected, leading to an "invalid index" error.
To prevent this, check if the notif window contains the static text element before accessing it.

-- Define the content to search for in the notification
set targetNotificationContent to "Running Backup Recently Modified"

-- Define how long the notification is displayed before being closed
delay 2

-- Use System Events to interact with UI elements
tell application "System Events"
	-- Access the notifications UI element
	tell process "Notification Center"
		-- Loop through each window (each notification is a window)
		repeat with notif in windows
			-- Check if the notification contains the target content
			try
				if (count of static texts of notif) > 0 then
					if (value of static text 1 of notif) contains targetNotificationContent then
						-- Close the notification
						perform action "AXPress" of button 1 of notif
						exit repeat
					end if
				end if
			end try
		end repeat
	end tell
end tell
1 Like

Did that solve the problem? If it did, please mark it as the solution.

1 Like

I forgot. Thanks for the reminder!