Table of contents
- Opening a Web Page in Safari
- Getting Information from an App
- Using Variables in AppleScript
- Combining Commands
In Part 1 [β], we learned the basics of AppleScript, including how to make your computer talk and how to create a folder in Finder. Now, letβs explore how to interact with other apps and get information from them.
AppleScript can be used to control any Apple app (and even some third-party apps). Letβs start by controlling Safari.
Opening a Web Page in Safari
In Script Editor, type:
01: tell application "Safari" 02: open location "https://www.google.com" 03: end tellClick Run.
This script opens Google in a new Safari window.
Breaking Down the Script
tell application "Safari"
tells your computer to control Safari.open location "https://www.google.com"
opens the web page.
Getting Information from an App
You can also get data from apps. For example, letβs ask Finder how many items are on your desktop:
Type the following in Script Editor:
01: tell application "Finder" 02: set itemCount to count of items in desktop 03: display dialog "There are " & itemCount & " items on the desktop." 04: end tellClick Run.
A message will pop up telling you how many items are on your desktop.
Breaking Down the Script
set itemCount to count of items in desktop
counts the number of items on your desktop and stores that number in a variable calleditemCount
.display dialog
shows a popup message with the result.
Using Variables in AppleScript
In the previous example, we used a variable (itemCount
). Variables allow you to store data and use it later in the script. You define a variable with set
and use it by simply referring to its name.
Combining Commands
You can combine multiple commands to automate more complex tasks. For example, letβs open Finder, count the items on your desktop, and then create a new folder if there are more than 5 items.
Type this in Script Editor:
01: tell application "Finder" 02: set itemCount to count of items in desktop 03: if itemCount > 5 then 04: make new folder at desktop with properties {name:"Too Many Items"} 05: end if 06: end tellClick Run.
This script checks if there are more than 5 items on your desktop. If there are, it creates a new folder called "Too Many Items."
Here is another article you might like π MacOS AppleScript Tutorial: Part 1 - Getting Started With AppleScript