MacOS – AppleScript: How to close notification alerts from a specific application

applescriptautomationmacosnotifications

In AppleScript, one can clear all notifications from all applications, like so:

tell application "System Events"
    tell process "NotificationCenter"
        set numwins to (count windows)
        repeat with i from numwins to 1 by -1
            click button "Close" of window i
        end repeat
    end tell
end tell

(Source)

Is it possible to clear the notifications from a specific application? For example, the script should remove the notifications from Calendar.app, but leave those that are from Google Chrome on the screen.


It may be necessary to explain what I intend exactly when I say, "clear." I am not trying to remove items from the list of notifications found in the "Notification Center" (i.e., the expandable vertical pane on the right side of the screen). I am trying to automate the action of pressing the "Close" buttons of the pop-up notifications that are superimposed in the top-right corner of the screen, so that these pop-up dialogs disappear from view.

This question concerns the "Alert" style of OS X notification (rather than the "Banner" style, which disappear on their own shortly after appearing).


OS X El Capitan, version 10.11.6.


Best Answer

I tested the following example AppleScript code under macOS 10.12.5, and it closed the Alerts style messages from Calendar.

tell application "System Events"
    tell process "NotificationCenter"
        set windowCount to count windows
        repeat with i from windowCount to 1 by -1
            if description of image 2 of window i is "Calendar" then
                click button "Close" of window i
            end if
        end repeat
    end tell
end tell

Note: This is example AppleScript code which contains no error handling. Add appropriate error handling as needed, required and or wanted.