EDDYMENS

Published a month ago

MacOS AppleScript Tutorial: Part 2 - Interacting With Apps And Getting Data

Table of contents

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

  1. In Script Editor, type:

    01: tell application "Safari" 02: open location "https://www.google.com" 03: end tell
  2. Click 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:

  1. 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 tell
  2. Click 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 called itemCount.
  • 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.

  1. 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 tell
  2. Click 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