I would like to click on the Wi-Fi icon with the option key down to reveal extra options available on Mac. How can I automate it using AppleScript?
I tried using key down option and click menu item but no luck in revealing special options.
Is there any way I can achieve this?
It's currently not possible to click with a key held down using AppleScript. Key down actions only apply to other key press actions, since the AppleScript click action doesn't actually perform a ‘click’, but rather directly actions the element.
If you don't mind using a 3rd party utility, here's an example AppleScript script that uses cliclick:
tell application "System Events"
tell application process "SystemUIServer"
set theWiFiProperties to item 1 of (get properties of every menu bar item of menu bar 1 whose description starts with "Wi-Fi")
end tell
set theXpos to (item 1 of position in theWiFiProperties) + ((item 1 of size in theWiFiProperties) / 2) as integer
set theYpos to (item 2 of position in theWiFiProperties) + ((item 2 of size in theWiFiProperties) / 2) as integer
end tell
tell current application
do shell script "/path/to/cliclick kd:alt c:" & theXpos & "," & theYpos & " ku:alt"
end tell
Note: Change /path/to/cliclick to the actual pathname of the cliclick executable.
How it works:
The theWiFiProperties variable gets set to the properties of the Wi-Fi menu extra and then the variables theXpos and theYpos get set to a position that together is the center of the Wi-Fi menu extra on the menu bar.
This info is then used in a do shell script command using cliclick to press the option key down, click at the designated x,y coordinates and let the option key up.
You can use Automator and record the process using “Watch me do” and then save the automated workflow as an application or a dictation command.
In Automator, I saved the watch me do action as an application. I named this new application “Extended_Wifi.app”. Then I had to add this application in system preferences to be able to control my computer.
Personally, I prefer to use Scripteditor rather than Automator because a huge part of me feels like using Automator is cheating. But at the end of the day, I was able to save the Automator action as an application and it functions perfectly however in Scripteditor, I Could not get the AppleScript version of the action to function correctly.
Here is a quick .gif showing the Automator application working correctly.
Related
How do I copy the result of the Calculator.app including decimals.
By defaults is selected, so if you just do a CMD+C it copies it into your clipboard. I got this code from #jweaks
set the clipboard to {?????}
I tried entering many different options but I don't know what I should put.
How do I copy the result of the Calculator.app including decimals.
set the clipboard to {?????}
As you already know ⌘C can do it, however, if you want to use a set clipboard to method, then here is one way to go about it:
Example AppleScript code:
if not running of application "Calculator" then return
tell application "System Events" to ¬
set the clipboard to ¬
(get the value of ¬
static text 1 of ¬
group 1 of ¬
window 1 of ¬
process "Calculator")
Notes:
Does not require Calculator to be frontmost.
Does not require the use of keystroke or key code to accomplish the task.
Can set the value to a variable instead of the clipboard, if wanting to process it in a different manner.
The example AppleScript code, shown below, was tested in Script Editor under macOS Catalina and macOS Monterey with Language & Region settings in System Preferences set to English (US) — Primary and worked for me without issue1.
1 Assumes necessary and appropriate settings in System Preferences > Security & Privacy > Privacy have been set/addressed as needed.
In testing, the Replies pane in Script Editor returned, e.g.,:
tell application "System Events"
get value of static text 1 of group 1 of window 1 of process "Calculator"
--> "6200.549407114624506"
set the clipboard to "6200.549407114624506"
end tell
Then when pasting into a document it pasted as: 6200.549407114624506
Update to address comments
To address the ensuing comments by sebseb under my answer and specifically…
Is it possible to run the script every time I hit enter on Calculator? then copy the result.
Basic vanilla AppleScript is not that intelligent and does not have the ability in of and by itself to understand what one is doing in Calculator and know when one has pressed the enter key to then place the result on the clipboard.
One would have to use an intermediary, an application like Hammerspoon, where it can wait for the Calculator application being activated/deactivated or its window being focused/unfocused to then enabled/disable trapping the enter key being pressed on the keyboard to then run the script to perform an action to calculate the result by pressing the = key then copy the result to the clipboard.
This works because pressing the = key in Calculator is equivalent to pressing the enter key, thus enabling trapping the enter key to perform the necessary actions using AppleScript. It quite possibly can be done without using AppleScript and just Lua, the language used by Hammerspoon and its API. However, since I already use various AppleScript scripts in conjunction with Hammerspoon and can easily recycle some existing code I'll present an addendum to the original answer using both methods in Hammerspoon.
The following example Lua code and API of Hammerspoon is placed in the ~/.hammerspoon/init.lua file.:
-- Create a hotkey used to trap the enter key and disable it.
-- It will then be enabled/disabled as Calculator is focused/unfocused
-- When enabled and the enter key is pressed it runs the AppleScript script.
local applicationCalculatorEnterHotkey = hs.hotkey.bind({}, "return", function()
local asFile = "/.hammerspoon/Scripts/CalculatorResultToClipboard.applescript"
local ok, status = hs.osascript.applescriptFromFile(os.getenv("HOME") .. asFile)
if not ok then
msg = "An error occurred running the CalculatorResultToClipboard script."
hs.notify.new({title="Hammerspoon", informativeText=msg}):send()
end
end)
applicationCalculatorEnterHotkey:disable()
-- One of two methods of watching Calculator.
--
-- The other is below this one and commented out.
-- Initialize a Calculator window filter.
local CalculatorWindowFilter = hs.window.filter.new("Calculator")
-- Subscribe to when the Calculator window is focused/unfocused.
CalculatorWindowFilter:subscribe(hs.window.filter.windowFocused, function()
-- Enable hotkey when Calculator is focused.
applicationCalculatorEnterHotkey:enable()
end)
CalculatorWindowFilter:subscribe(hs.window.filter.windowUnfocused, function()
-- Disable hotkey when Calculator is unfocused.
applicationCalculatorEnterHotkey:disable()
end)
-- Alternate method to wait for Calculator and enable/disable the hotkey.
--
-- Uncomment below method and comment the above method to test between them. Adding the
-- multiple line opening '--[[' and closing '--]]' to above method and removed from below,
-- leaving 'local CalculatorWindowFilter = hs.window.filter.new("Calculator")' uncommented.
--[[
function applicationCalculatorWatcher(appName, eventType, appObject)
if (eventType == hs.application.watcher.activated) then
if (appName == "Calculator") then
-- Enable hotkey when Calculator is activated.
applicationCalculatorEnterHotkey:enable()
end
end
if (eventType == hs.application.watcher.deactivated) then
if (appName == "Calculator") then
-- Disable hotkey when Calculator is deactivated.
applicationCalculatorEnterHotkey:disable()
end
end
end
appCalculatorWatcher = hs.application.watcher.new(applicationCalculatorWatcher)
appCalculatorWatcher:start()
-- appCalculatorwWatcher:stop()
--]]
The following example AppleScript code is used in conjunction with Hammerspoon and is saved as CalculatorResultToClipboard.applescript in ~/.hammerspoon/Scripts/, and you'll need to create the hierarchical folder structure.
Example AppleScript code:
One can use either:
tell application "Calculator" to activate
tell application "System Events"
key code 24
delay 0.5
set the theResult to the value of static text 1 of group 1 of window 1 of process "Calculator"
end tell
set the clipboard to theResult
Or:
tell application "Calculator" to activate
tell application "System Events"
key code 24
delay 0.5
key code 8 using command down
end tell
To accomplish the task.
An alternate option, as previously mentioned, is to forgo the use of AppleScript and use the following example Lua code:
local applicationCalculatorEnterHotkey = hs.hotkey.bind({}, "return", function()
-- Press the '=' key to finish the calculation.
hs.eventtap.keyStroke({}, "=")
-- Copy the result to the clipboard.
hs.eventtap.keyStroke({"cmd"}, "C")
end)
applicationCalculatorEnterHotkey:disable()
This function would be used instead of the same function further above. It replaces the execution of the AppleScript script with keystrokes generated by Hammerspoon to accomplish the same tasks, while using the remaining example Lua code and the API of Hammerspoon already presented.
Notes:
With the example Lua code, as coded, the behavior of pressing the enter key is only trapped and modified to trigger the example AppleScript code, or if using the alternate option send Hammerspoon keystrokes, while Calculator has focus. The enter key should work normally in all other applications.
See my other Hammerspoon related answers for instructions to install it and utilize the information contained herein.
One in particle is:
A: How can I make preview stop wrapping around when paging?
If using Script Editor, the example AppleScript code is saved as Text in the File Format: pop-up menu in the Save dialog box.
The example Lua code and API of Hammerspoon and AppleScript code, shown directly above, were tested respectively with Hammerspoon and Script Editor under macOS Mojave and macOS Catalina with Language & Region settings in System Preferences set to English (US) — Primary and worked for me without issue1.
1 Assumes necessary and appropriate settings in System Preferences > Security & Privacy > Privacy have been set/addressed as needed.
Calculator.app doesn't have an AppleScript dictionary.
You have to script the UI with System Events
tell application "System Events"
tell process "Calculator"
set frontmost to true
keystroke "c" using command down
end tell
end tell
I've recently found Applescript after desperate hours trying to figure out a way to do the trick since I use Preview A LOT. The button to open highlighting colors doesn't have any menu item or keyboard shortcut (only for general highlight that is yellow, my plan was to create shortcuts for the rest of the colors available), it's only located in the toolbar. The code I've encountered for similar problems didn't work (probably due to my serious lack of knowledge in the area...), so if anyone could come up with something I would really appreciate it!
First I'd like to make note that Preview does not contain an AppleScript dictionary file, e.g. Preview.sdef, and as such, sans a minimal set of default commands, is not easily scriptable beyond the default commands and requires UI Scripting with System Events to achieve the goal.
Note that UI Scripting can be kludgy and has its own issues and requires granting privileges in System Preferences > Security & Privacy > Privacy > Accessibility, which one should be prompted for if necessary, however I present two options for your consideration.
Option 1
This first option simply triggers the Highlight menu where you can then press the key of the first character of a color, after which you press the enter to set the chosen color. For the color Purple, since there is also Pink, pressing P will of course highlight Pink, so pressing Pu will select Purple. You can also use the Up/Down arrow keys to navigate the menu.
This would allow you to actuate the menu with one assigned keyboard shortcut and not have to explicitly assign a keyboard shortcut for each individual color.
Example AppleScript code:
tell application "Preview" to activate
delay 0.1
tell application "System Events"
tell group 2 of ¬
toolbar 1 of ¬
window 1 of ¬
application process "Preview"
try
click menu button 1 of group 1
on error
click menu button 1 of radio group 1
end try
end tell
end tell
Note: In the example AppleScript code shown above make note that there is an try statement with error handling to click the target menu. This is because the hierarchical UI element structure changes based on whether or not highlighting has already been used in the current document. This also allows for the script to silently fail if the keyboard shortcut to trigger it is pressed on a document that highlighting cannot be preformed on.
Option 2
This next option presents a list to choose from and then sets the highlight color based on the selection.
Example AppleScript code:
set colorList to ¬
{"Yellow", "Green", "Blue", "Pink", "Purple"}
set chosenHighlightColor to ¬
(choose from list colorList ¬
with title "Select Highlight Color") ¬
as string
if chosenHighlightColor is "false" then return
tell application "Preview" to activate
tell application "System Events"
tell group 2 of ¬
toolbar 1 of ¬
window 1 of ¬
application process "Preview"
try
click menu button 1 of group 1
on error
click menu button 1 of radio group 1
end try
delay 0.05
try
click menu item chosenHighlightColor of menu 1
end try
end tell
end tell
Note: In the example AppleScript code shown above make note that there is an try statement with error handling to click the target menu. This is because the hierarchical UI element structure changes based on whether or not highlighting has already been used in the current document. This also allows for the script to silently fail if the keyboard shortcut to trigger it is pressed on a document that highlighting cannot be preformed on.
Automator Service/Quick Action and Keyboard Shortcut
To use either of these examples as a keyboard shortcut, create an Automator Service/Quick Action with a Run Shell Script action replacing the default code with the example AppleScript code.
Then in System Preferences > Keyboard > Shortcuts > Services assign it a keyboard shortcut. I used ⇧⌘H as it was not already assigned to anything in Preview.
Notes:
This was tested and worked for me as is under macOS Catalina and macOS Big Sur with Language & Region setting in System Preferences set to English US.
Does not work if the document is in Full Screen view.
Select Highlight Color
Automator Service/Quick Action
Note: The example AppleScript code is just that and sans any included error handling does not contain any additional 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.
I am working with Selenium on macOS to automate sending images using WhatsApp web in Google Chrome. The task involves uploading the image, and for that a system(Finder) prompt comes up to select the file. It's done in Windows using AutoIt.
I tried looking up how to automate this task in macOS, and I believe AppleScript can be used for it. Since I have no experience in GUI scripting, any help would be appreciated.
Thanks.
I was able to find the answer on another post on Stack Overflow. I have added the answer for anyone who comes across the same problem.
tell application "System Events"
keystroke "G" using {command down, shift down}
delay 1
keystroke "/path/to/file"
delay 1
keystroke return
delay 1
keystroke return
delay 1
end tell
I don't advocate GUI scripting any more than the burning down of the Amazon, but it seems to be necessary for this task, and I wanted to provide you with an example of a GUI script that tries its best to minimise the unpleasantness of the user experience, and aim for fewer weak points in the code where GUI scripts are most likely to falter.
If you know the path to your file—which I assume you do in these sorts of situations, as your script keystrokes the filepath—then you might find the following technique saves a few steps, and feels a bit more graceful in how it gets executed:
set filepath to "/path/to/image.jpg"
-- Copy file object to clipboard
set the clipboard to filepath as «class furl»
-- Make sure Chrome is in focus and the
-- active tab is a WhatsApp tab
tell application id "com.google.Chrome"
activate
if the URL of the active tab in the front window ¬
does not contain "web.whatsapp.com" then return
end tell
-- Paste the clipboard contents
-- and hit return (send)
tell application id "com.apple.SystemEvents"
tell (process 1 where it is frontmost) to tell ¬
menu bar 1 to tell menu bar item "Edit" to tell ¬
menu 1 to tell menu item "Paste" to set Paste to it
if (click Paste) = Paste then keystroke return
end tell
The if (click Paste) = Paste check should negate the need for a delay, as it explicitly forces AppleScript to evaluate the click command before going on to issue a keystroke. However, I can't test this under all possible conditions, and if there are other factors, like CPU usage, or process freezes, that are likely to give the script a chance to jump ahead, then just insert a small delay after then and move keystroke return down onto its own line.
If you wish to remove the file object from the clipboard afterwards, then simply add as the final line set the clipboard to (and just leave it blank after the word "to", which will clear the clipboard's contents). Of course, this won't affect any clipboard history data you might have if you use a clipboard managing app, only the system clipboard's current item.
I can't manage to find how to use the selected text as a variable for AppleScript and Automator.
Any ideas?
For Applescript, it works with other applications. To get the selected text of the front window in an app, Applescript has to use the language/syntax that this app understands/responds to. For very scriptable, text document based apps, there is much similarity, looking something like:
tell app "xyz" to get selection of document 1
However, there really is no standard. Many apps don't have a 'text selection' object in their scriptable dictionary, so you have to do all kinds of workarounds. See these examples:
tell application "Safari" to set selectedText to (do JavaScript "(''+getSelection())" in document 1)
tell application "System Events" to tell application process "TextEdit" to tell attribute "AXSelectedText" of text area 1 of scroll area 1 of window 1 to set selectedText to its value
tell application "Microsoft Word" to set selectedText to content of text object of selection
You can also script "System Events" to simulate the keystroke of command-c in order to copy text.
tell application "System Events" to keystroke "c" using {command down}
delay 1
set selectedText to the clipboard
If you need more specific help, post your code and indicate what app you are working with. If it is not a scriptable app, then you'll have to use the last method, calling System Events. Or, it's possible you can use an OS X Service, which you also asked about.
When you create a Service in Automator, you create a new Workflow of the type Service. Then, simply make sure that at the top of the window it says:
"Service receives selected text".
You can then use Automator actions to interact with the selected text that gets passed to the actions that follow.
Not all programs are compatible with Services, unfortunately.
To see how it works, try this very simple Automator service:
Create a Service in Automator and choose Text and Every application as input.
The first workflow step is Execute Applescript.
The Applescript's input parameter contains the selected text.
Set the Applescript to
on run {input, parameters}
display dialog (input as text)
return input
end run
After saving, you will have this action available in the context menu whenever you have selected text.
Maybe the naming is different, I don't know the English descriptions. But I hope this is a good starting point for you.
Have fun, Michael / Hamburg
I am currently using applescript to setup various parameters of the desktops at my university. So far my script successfully changes the desktop background and the dock size.
The problem at hand is when I run the script, majority of the time, the icons on the desktop never change.
Here is the script I wrote to alter the desktop icon's size and grid spacing:
tell application "System Events"
set finderPrefsFile to property list file "~/Library/Preferences/com.apple.Finder.plist"
tell finderPrefsFile
tell property list item "DesktopViewSettings"
tell property list item "IconViewSettings"
set value of property list item "gridSpacing" to "100"
set value of property list item "iconSize" to "32"
set value of property list item "arrangeBy" to "none"
end tell
end tell
end tell
end tell
#Restart Finder for changes to take effect.
do shell script "killall Finder"
How should I go about altering the script to make it work all the time (I would like to eventually share this script with some of my classmates).
P.s.
Here is the full script
I didn't get your script work reliable. I played around with timeouts but didn't get the Finder to refresh using the new settings.
But I found to set some view options directly using vanilla AppleScript:
tell application "Finder"
activate
set iconViewOptions to desktop's window's icon view options
tell iconViewOptions
set arrangement to not arranged
set icon size to 32
set shows item info to false
set shows icon preview to false
end tell
quit
end tell
delay 1
tell application "Finder" to activate
The AppleScript quit-handler works more reliable then do shell script "killall Finder", maybe the killall is too hard...
The delay 1 does the magic to give the Finder the time to breath before get up again and using it the Script works each time...
But one thing is AFAIK not possible in Finder scripting: Setting the grid space :-/
Greetings, Michael / Hamburg