Get text of most recent notification with applescript
I would like to be able to grab the text of the most recent notification and pass it into an applescript variable. How can I do that?
Edit: here's what I have so far:
on run
tell application "System Events"
tell process "NotificationCenter"
tell first window
set rawElements to UI elements
end tell
end tell
end tell
end run
This gets me most of the way there, but it doesn't get me the body of the notification, just the label:
Here's the output:
{static text "Macro Cancelled" of window 1 of application process "NotificationCenter" of application "System Events", image 1 of window 1 of application process "NotificationCenter" of application "System Events", scroll area 1 of window 1 of application process "NotificationCenter" of application "System Events", image 2 of window 1 of application process "NotificationCenter" of application "System Events"}
Using the following example AppleScript code to generate a notification:
display notification with title "Macro Cancelled" subtitle "Cancel All Macros."
In the example notification, Cancel All Macros. is in:
static text of scroll area 1 of window 1 of process "NotificationCenter"
Using:
tell application "System Events" to ¬
get value of ¬
static text of ¬
scroll area 1 of ¬
window 1 of ¬
process "NotificationCenter"
It returns:
{"Cancel All Macros.", ""}
As you can see what's returned is a list
and will need to be process as such.
Note however, in this example, Cancel All Macros. is actually static text 1 of scroll area 1
and static text 2 of scroll area 1
, which is blank, is when display notification
uses:
- display notification [text] : the body text of the notification
Note: The example AppleScript code is just that and does not contain any error handling as may be appropriate. The onus is upon the user to add any error handling as may be appropriate, needed or wanted. Have a look at the try statement and error statement in the AppleScript Language Guide. See also, Working with Errors. Additionally, the use of the delay command may be necessary between events where appropriate, e.g. delay 0.5
, with the value of the delay set appropriately.
With Error Handling:
tell application "System Events" to ¬
if exists window 1 of ¬
process "Notification Center" then ¬
get value of ¬
static text of ¬
scroll area 1 of ¬
window 1 of ¬
process "NotificationCenter"