macOS 13 Ventura で全ての通知を閉じるスクリプト

macOSの通知で、個々の通知をクリックするまで残しておきたいケースでは、通知のスタイルを「通知パネル」にし、かつ「通知をグループ化」をオフにして利用します。
(私の場合は Slack の自分宛メッセージの通知などでこうしています。)

しかし、時には通知が(場合によっては自動的に)大量に発行され、画面に大量に溜まってしまう、なんていうこともあります。
こんな時に一気に閉じたくなりますがそういったボタンはなく、連打してもゆっくり消えるアニメーションが入るためになかなか閉じられずにストレスになります。。

そんな時のために一気に閉じる AppleScript を用意しておくと良いでしょう。
似たようなスクリプトはあちこちで見つかりますが、内部的な通知センターのUIの作りに依存しているため、OSのバージョンが異なったりすると動作しません。
以下は Ventura で動作を確認しているものです。

なお、各通知に対して下から順番に閉じるアクションを発行してもなぜか一部の通知が閉じずに残ったりする時があるので、何度かループしてやり直すという苦肉の策をとっています。

スクリプトエディタに下記を入力して、アプリケーションとして保存してダブルクリックで利用できます。なお初回実行時に許可を求められるので、保存したアプリケーションを「設定 > プライバシーとセキュリティ」の「オートメーション」と「アクセシビリティ」でアクセスを許可しておく必要があります。


activate application "NotificationCenter"
tell application "System Events"
	tell process "NotificationCenter"
		tell UI element 1 of scroll area 1 of group 1 of window "Notification Center"
			set loop to true
			
			repeat while loop
				set theWindows to every UI element as list
				set n to (count theWindows)
				set closedCount to 0
				repeat with i from n to 1 by -1
					try
						set theWindow to item i of theWindows
						set theActions to actions of theWindow
						repeat with theAction in theActions
							if description of theAction is "Close" then
								tell theWindow
									set closedCount to closedCount + 1
									perform theAction
									exit repeat
								end tell
							end if
						end repeat
					end try
				end repeat
				if closedCount = 0 then
					set loop to false
				end if
			end repeat
		end tell
	end tell
end tell