To make GUI Scripting and access the contextual menu could be tricky.
I have test this on Safari and Finder and every application is different.
This example use ‘Finder’ so the first line in the code will activate it.
activate application “Finder”
This is the code that give the information we need.
tell application "System Events"
set theApplication to first application process whose frontmost is true
set theControl to value of attribute "AXFocusedUIElement" of theApplication
end tell
This is the result of the above code.
We will copy the code from outline 1 → window and include 1 so we will have a line of this
and include in the end of above line with
Now we will have a function to access contextual menu in ‘Finder’
tell application "System Events" to tell application process "Finder"
set frontmost to true
tell outline 1 of scroll area 1 of splitter group 1 of splitter group 1 of window 1 to perform action "AXShowMenu"
end tell
It could be a good advice to select a item first in Finder before execute below code.
tell application "System Events" to tell application process "Finder"
activate
--> COPY THE CODE BELOW TO HERE
end tell
To access the ‘Services’ menu could look like this…
tell window 1
tell splitter group 1
tell splitter group 1
tell scroll area 1
tell outline 1
perform action "AXShowMenu"
tell menu 1
get the name of every menu item
{"Open in New Tab", "Open in New Window", missing value, "Move to Trash", missing value, "Rename", "Compress", "Compress", "Quick Actions", missing value, "Copy “”", "Import from iPhone", missing value, "Use Groups", "Sort By", "Show View Options", missing value, missing value, missing value, "Services"}
click menu item "Services"
end tell
end tell
end tell
end tell
end tell
end tell