You are using an outdated browser. Please upgrade your browser to improve your experience.

How to get started with macOS AppleScript: dictionaries, syntax, and more

Chip Loder's Avatar

AppleScript was born in the early 1990's at Apple in an attempt to modernize the Mac's OS. It was partly derived from an earlier script language designed by one of the original Mac architects - Bill Atkinson who wrote the original Mac's graphics system, QuickDraw.

On the early Mac, Atkinson designed a card-based development environment called HyperCard , and a scripting language to go with it called HyperTalk. Developers could attach small HyperTalk code snippets to user interface elements such as buttons, text fields, and lists.

Apple, however, wanted a way to script and control the entire Mac OS, not just one application. Some elements of HyperTalk were commandeered, and other scripting elements were added. The result was AppleScript.

First released thirty years ago along with the first color version of the Mac OS, System 7 , the Mac also shipped with a lightweight Script Editor application, which lives on to this day in macOS.

In the 1990's a slew of third-party AppleScript developer tools appeared, including Facespan and UserLand Frontier .

Facepsan development environment on Mac OS 9.

Getting Started

AppleScript and macOS's Script Editor app allow you to write and optionally record scripts that have targets in macOS that they can be directed at. The AppleScript language is fairly easy and English-like and is a breeze to learn.

Designed for simplicity, most AppleScripts follow a subject-verb model where you first state which object or objects you are directing your commands at, then you tell those objects what to do. Objects can be apps, windows, UI elements, or data within an application.

The AppleScript Editor window looks like this:

AppleScript Editor.

At the top of the window is a pane where you type your script in, and the bottom pane is used for both output and debugging.

You can check the syntax of your script for accuracy by clicking the Compile (hammer) button in the toolbar. AppleScript Editor will compile your script and highlight any errors.

If the script compiles successfully, you will see all its syntax coloring change to that defined in the Settings window. We'll get to the Settings window below in a moment.

Once compiled, click the Play button in the toolbar to run your script, and click the Stop button to stop it.

You can also record scripts from other apps by pressing the Record button and then going to another app and performing some action. The app being recorded must be written to support AppleScript recording.

Once you're done recording, come back to AppleScript Editor and press the Stop button.

Architecture

AppleScript is based on an underlying technology called the Open Scripting Architecture (OSA). Apple designed OSA purposely to allow other scripting languages to be plugged in and used to automate the Mac. AppleScript is but one OSA language.

Later Apple added JavaScript support to OSA, which now allows JavaScript to be used to control the Mac as well.

At an even lower level is another Apple technology called AppleEvents (AE). AppleEvents are an Inter-Application Communication (IAC) facility which allows apps and processes to communicate with each other.

AppleEvents usually have a four-character code for the class, or suite of events, then another four-character code for the event type itself. By sending and receiving AppleEvents, macOS apps can trigger each other to perform certain actions.

AppleScript is based on AppleEvents and uses the IAC mechanism to transport messages and data around the system.

Dictionaries, terminology, and suites

In order for AppleScript to work, apps have to define and publish which events they support. By doing so they advertise to other apps how they can be controlled.

In most cases in macOS, AppleScript-enabled apps define AppleScript dictionaries which define which events and script elements they support and how those events are triggered externally. By publishing dictionaries, other apps can see how to control apps using AppleScript.

Each dictionary defines scripting terminology and one or more AppleEvent suites - and within each suite, events. There are several publicly available utilities for viewing AppleScript dictionaries contained inside apps.

These dictionaries are especially critical when recording an AppleScript from an app since the recording system relies on reading and receiving events and data defined in the dictionaries. The dictionaries are also used by Script Editor to validate and check AppleScript code before running it.

Apple itself defines several suites such as the Core Suite, the Finder Suite, and others. Third-party apps can define their own suites as well.

Viewing dictionaries and suites

AppleScript Editor has a built-in AE dictionary viewer. To access it, run Script Editor, then select File->Open Dictionary . macOS already knows which apps on your Mac publish script dictionaries so it only displays those apps in the list:

The Open Dictionary window.

To view any app's scripting dictionary, select it from the list and click the Choose button. The browser disappears and the dictionary window opens:

Scripting Dictionary viewer.

In the dictionary window's upper left pane is a list of AE suites the app supports. Single-click any suite to view all its supported events in the pane to the right of it.

In this case, in Apple's Bluetooth File Exchange app, it defines one AE suite, Bluetooth File Exchange Suite, which contains two events: browse and send.

In the pane at the bottom of the dictionary window, each command or event is listed, along with its syntax - namely an object to send the message to. In this case, there are two object types, text and file.

Note the command hierarchy - in the case of send there is the command, then the file to send, then the device to send it to. This nested pattern is everywhere in AppleScript.

One of the initial concepts you'll have to get used to when writing AppleScript is that of containers . Everything is contained inside something else, except for top-level objects.

So when writing scripts you typically "tell" an application to do something or fetch or set something inside of something else, inside of yet something else modified by something else. Additional info is provided in AppleScript using modifiers - the equivalent of English elements like "as" or "with".

"of" is often used in AppleScript to drill down through the container hierarchy.

So for example you might tell a tab group of a certain window to select one tab, then perform some action. AppleScript syntax is highly nested.

In AppleScript, nearly everything is considered an object , which is an encapsulation of both code and data. Objects can send and receive messages (called methods), and data which those methods act on.

Also on the right side of the dictionary window's toolbar is a popup menu that allows you to select which language you want to view the suites' descriptions in. Currently, AppleScript, JavaScript, and Objective-C are supported.

Objective-C is Apple's C-based object programming language which much of macOS is written in. It was inherited from macOS's predecessor, NeXTStep, which Apple acquired in 1997 when it bought Steve Jobs' other company, NeXT, Inc.

The hidden AppleScript Utility

Originally macOS shipped with an app called AppleScript Utility which is hidden away in /System/Library/Core Services. You used to be able to run this app to set up how AppleScript behaves but most of its options are now accessible from within the main Script Editor app which lives in /Applications/Utilities.

To get started, launch Script Editor, then select Script Editor->Settings to open the Settings window:

The Settings window.

There are four tabs in the Settings window:

Editing and Formatting allow you to set text details in the Script Editor window such as fonts, colors, indenting, suggestions, and line wrapping.

History provides features such as logging, and the number of log entries.

In the General tab you'll find many of the features previously controlled by Script Utility. This includes whether to use AppleScript or JavaScript, whether to show or hide the "tell" application menu, settings for the dictionary viewer, and whether to show or hide the AppleScript menu bar icon (which we'll get to in a moment).

You can also choose an app for editing scripts. In fact, you don't need to use Script Editor to edit scripts. Any text editor will do - you can later import or copy and paste scripts into Script Editor to run.

The one big advantage Script Editor has is syntax highlighting and debugging since you can both edit and run your scripts in the same window.

If you select the Show Script menu in menu bar checkbox in Settings, macOS adds a script menu to the menu bar. From this menu, you can open Script Editor, open the built-in scripts folder that lives in /Library/Scripts on your Startup Disk, or run one of macOS's built-in scripts directly:

The Scripts menu bar item

AppleScript syntax

There are several syntax constructs (keywords) you'll see time and again in AppleScript. Some of the common ones are:

In addition, there are several verbs in AppleScript such as tell, open, choose, is, set, repeat, copy, try, and others.

'end' can be combined with tell, if, repeat and other commands to form blocks of code. Most nested verb blocks must be ended with an 'end' in order to maintain flow control throughout the program.

The special verb 'return' is used to break out of a block of code and return to a previous execution point in the program.

There are also adverbs that usually follow or modify verbs - such as with and without .

Handlers and properties

AppleScript provides handlers - special functions which can be called from another script or elsewhere in the system. There are several standard AppleScript handlers such as open and run .

When an AppleScript is first launched, the open handler is run. This handler allows you to set up initial conditions for the script. Another common handler is run , which gets executed after the open handler.

A property is a named variable which can be set to some value to be used or modified later. For example:

property ChooseScriptPrompt : "Select compiled script file(s) containing folder actions"

This defines a property named ChooseScriptPrompt whose initial value is set to the string of text after the ":". The ":" is required.

Properties are usually defined all at once at the top of AppleScripts.

Named functions

You can also define your own named functions of AppleScript, then call them from elsewhere in the script. use the to keyword followed by a function name and empty parenthesis to define a function. For example:

to ChooseFileFromFAScriptFolder()

(some code)

end ChooseFileFromFAScriptFolder

Each named function must be ended with the "end" keyword followed by the same function name. The names must match exactly or you'll get a syntax error.

To call custom functions from elsewhere in an AppleScript, use the keyword "my" followed by the function name and an empty parenthesis. For example:

my ChooseFileFromFAScriptFolder()

open the result

The special variable result is reserved for the value returned by a function. After running, result will contain whatever that function returns.

Inside a function, you use the return keyword to force a function exit - an optional return value is sent back to the calling function. For example:

return SelectedScripts

Interrogating objects

Objects in AppleScript have a class - which describes the type of object. You can find out the class of an object using the class keyword. For example:

if class of ChosenScripts is boolean then

error number -128

In this example class' asks ChosenScripts what kind of object it is and if the result is boolean (true or false), then it sets an error number, otherwise, it does nothing.

Note there are actually two classes being used here - boolean and number . AppleScript Editor provides handy syntax highlighting so you can easily identify built-in class names.

Using the filesystem

Often in AppleScript, you'll want to tell an app to access an object on disk. There are several built-in objects for doing this, among them folder , file , and path .

There are also several built-in modifiers for standard locations in the macOS filesystem - for example the user folder or special folders such as Folder Action scripts:

set UserScripts to list folder (path to Folder Action scripts folder from user domain) without invisibles

The path to construct in parenthesis shown above tells AppleScript to evaluate and resolve that expression first as a path to a folder, then process the rest of the line. Usually path to expressions get reduced to a single filesystem path, then passed to some other command for processing.

In the above example we're getting the path to the Folder Action scripts folder in the user folder, then storing its contents as a list in the variable UserScripts , excluding any invisible files.

Once set, the variable UserScripts can then be used anywhere else in the script to indicate the list of items in the folder at that path on disk.

In AppleScript, you can add single-line or multi-line comments, which are ignored by the compiler.

Single-line comments are indicated by a double-dash ( -- ) at the start.

Multi-line, or block comments are bracketed by (* and *) . For example:

Get User Name

This script uses UI element scripting to get the name of the current user.

Copyright 2013 Apple Inc.

Single-line comments can go just about anywhere in a script - on lines by themselves, or at the end of lines.

Saving AppleScripts

Currently, Script Editor supports saving scripts in four formats:

  • Script bundle
  • Application

'Script' saves an AppleScript in Script Editor's native uncompiled format.

'Script bundle' saves an AppleScript in Script Editor's native format but can include additional resources such as external files.

'Application' saves an AppleScript into a precompiled executable format which can be double-clicked in Finder or launched by another process without Script Editor.

'Text' saves a script as plain text which can be opened with any text editor.

To save an AppleScript, press Command-S on the keyboard, enter a name, select a File Format from the popup menu, and click the "Save" button.

The Save panel.

If you selected Application from the File Format popup when saving, two additional checkboxes are enabled: Show startup screen , and Stay open after run handler .

Selecting the first checkbox causes the script to show a run confirmation window on launch, and selecting the second checkbox forces the script to stay open after the run handler completes.

Application options.

If you hold down the Option key on the keyboard and select File->Save from the menu bar, the Save command changes to Save As which allows you to save a new copy of the script under another name.

Putting it all together

Now let's take a look at a sample script and analyze it line by line. We'll use the built-in Probe Menu Bar script found in the /Library/Scripts/UI Element Scripts folder on the Startup Disk in macOS.

This script starts with a try and end try block. try is a keyword that allows you to run a block of code and trap for an error if one occurs. try blocks must end with end try .

You can nest try blocks to control program flow.

To handle an error in a try block, use the on error syntax as used in this script. on error always goes after the try line but before the end try line:

on error errMsg

display dialog "Error: " & errMsg

In this example, if an error occurs, the script displays a simple dialog with the message "Error: " followed by the contents of the variable errMsg .

Next in the script, we see three nested tell blocks which each have an end tell line at the end of each block. You use tell to direct a block of code to some object - in this case, the system handler, but it can also be another app, a filesystem object, some UI element in an app, or even data.

In this example the first tell block tells the system to get all available properties, then to get a list of all running processes:

tell application "System Events"

get properties

get every process

In the next tell block the script tells Finder to get all the menu bars of all running apps, then to iterate each menu bar and get every item contained in every menu in all the menu bars. This gets quite redundant:

tell process "Finder"

get every menu bar

tell menu bar 1

get every menu bar item

get every menu of every menu bar item

get every menu item of every menu of every menu bar item

get every menu of every menu item of every menu of every menu bar item

get every menu item of every menu of every menu item of every menu of every menu bar item

From this code, you'll soon realize one of the strangest aspects about AppleScript programming: namely that when you want to access an object you must first consider the most distant or outermost object, then work your way back from there.

This is the reverse of the way most object-oriented programming languages work in which you start with the top object and dive down from there to access its members.

This syntax can often make AppleScript annoying since it's usually the reverse logic of the thing you're trying to get at.

Finally, the script displays a simple dialog box with a message:

display dialog "The 'Probe Menu Bar' script was executed, it uses UI element scripting to return a list of every menuitem

of every menu for every application currently running, to see results run it within AppleScript Editor."

For reference, here's the full complete script listing:

Probe Menu Bar

This script uses UI element scripting to return a list of every menuitem

of every menu for every application currently running.

You may incorporate this Apple sample code into your program(s) without

restriction. This Apple sample code has been provided "AS IS" and the

responsibility for its operation is yours. You are not permitted to

redistribute this Apple sample code as "Apple sample code" after having

made changes. If you're going to redistribute the code, we require

that you make it clear that the code was descended from Apple sample

code, but that you've made changes.

After you run your script, if you click the tiny list-like icon in the lower-left corner of the window, two additional icons appear on the pane separator on the right side of the window: a trash can, and a clock. If you click the clock icon, a log window appears which contains any log messages while the script was running - unless you've turned logging off in the Settings window:

Log History window.

You can click on each item in the log window on the left to see details about each message or event which got logged.

We've barely scratched the surface of AppleScript here. In future articles, we'll dive more in-depth into syntax, special keywords, terminology, recording, scripting addition plug-ins, third-party tools, and Apple's other automation app, Automator .

Top Stories

article thumbnail

Apple's MacBook Air with 16GB RAM, 512GB SSD drops to record low $1,239

article thumbnail

AI computer showdown - MacBook Air vs. Microsoft Surface Laptop Copilot+ PC

article thumbnail

All-screen foldable MacBook may come in multiple sizes with M5 processor

article thumbnail

Siri for iOS 18 to gain massive AI upgrade via Apple's Ajax LLM

article thumbnail

iOS resurrected photo bug fixed with iOS 17.5.1 detailed by Apple

article thumbnail

Your next iPhone could be the iPad mini - iPhone 15 vs iPad mini showdown

Featured deals.

article thumbnail

Today's MacBook Pro price war knocks $300 off Apple's M3 Max 16-inch with 48GB RAM

Latest exclusives.

article thumbnail

Apple set to deliver AI assistant for transcribing, summarizing meetings and lectures

article thumbnail

Apple to unveil AI-enabled Safari browser alongside new operating systems

article thumbnail

System Settings getting shuffled again in macOS 15, among other UI tweaks

Latest comparisons.

article thumbnail

13-inch tablet power compared — iPad Pro vs iPad Air

article thumbnail

Flagship iPad head-to-head — M4 iPad Pro vs M2 iPad Pro compared

article thumbnail

iPad Air shootout — 2024 M2 iPad Air vs M1 iPad Air compared

Latest news.

article thumbnail

Apple saw a huge year-over-year iPhone sales recovery in China in April

China's main market research company is out with its latest data, and as the iPhone 16 creeps closer, the iPhone 15 is continuing its recovery in the country.

author image

Apple's 1TB 14-inch MacBook Pro M3 Pro just dropped to the lowest price ever

The month-end special knocks $230 off the latest 14-inch MacBook Pro with an upgrade to 1TB of storage. Grab the exclusive deal for three days only.

author image

How to fill out and sign PDF forms on iPhone and iPad

Sometimes you need to sign or fill out PDF forms while you're away from your Mac. Here's how to get that paperwork done on your iPhone or iPad.

author image

The upgraded M2 MacBook Air featuring 16GB unified memory and 512GB of storage is $160 off, marking the lowest price on record — just in time for graduation and Father's Day gift-giving.

article thumbnail

This Lego Apple Store model needs votes for a slim chance of getting made

A Lego Apple Store has surfaced on Reddit as its creator hopes to get enough votes to make it into an official Lego set — but it probably won't happen.

author image

Apple's iPad Pro designers talk about thinness and the Apple Pencil shadow

In a rare interview, key Apple designers reveal why they gave the new Apple Pencil that digital shadow, and how it's part of their overall goal for the iPad Pro.

author image

Interview with Ecobee CEO Greg Fyke, affordable home key lock, & Sonos headphones on HomeKit Insider

On this episode of the HomeKit Insider Podcast, Sonos launches a pair of new smart products, a new affordable Home Key lock emerges, and Ecobee CEO Greg Fyke joins us to talk about the future of home automation.

author image

At launch, Apple said that the M3 MacBook Air is the fastest consumer-grade AI laptop, and Microsoft's has arrived to challenge it. Can Microsoft claim the crown with the Surface Laptop Copilot+?

author image

How to easily see what was talked about at every WWDC session since 2000

There is an easy way to see a list of everything Apple talked about at WWDC sessions since 2000, without manually combing through Apple's pages. Here's how to do it.

article thumbnail

OpenAI is releasing a ChatGPT app for Mac first, well ahead of Windows

OpenAI is debuting its own app for ChatGPT generative text for macOS users, and it will be released very shortly after the release event is over.

article thumbnail

Apple has a new Swift tutorials webpage for budding developers

Apple has launched a new tutorial webpage featuring beginner resources for programming using Swift, Swift UI, and Xcode.

Latest Videos

article thumbnail

Retro gold rush: which emulators are on the App Store, and what's coming

article thumbnail

iPad, iPad Air, iPad Pro buyer's guide May 2024: which iPad to buy for any budget

article thumbnail

iOS 17.5 is here with Repair State & EU Web Distribution

Latest reviews.

article thumbnail

Waterfield Shield Case for Apple Vision Pro review: Way better for travel than Apple's case

article thumbnail

Keychron Q1 HE Review - Near-infinitely adjustable keyboard with impressive design

article thumbnail

Atoto S8 Pro Wireless CarPlay receiver review: great, but fragile aftermarket solution

article thumbnail

{{ title }}

{{ summary }}

author image

  • iPod + iTunes
  • The Principles Remain the Same

In this chapter, you’ve been introduced to the fundamental principles and structures of the AppleScript language. These principles include the following essential concepts:

  • Scriptable objects have properties with corresponding values.
  • Scriptable objects can also contain other scriptable objects that also have properties with corresponding values.
  • The values of the properties of scriptable objects can be read and sometimes altered.

In learning to apply these principles, you wrote scripts to control the appearance of Finder windows in the Finder application by accessing and changing the values of their properties and by using standard verbs, such as close and open, to control their display. As stated earlier in this chapter, the principles used in those scripts apply to all scriptable applications, not just the Finder application.

Let’s see whether that statement is indeed true.

In a new Finder window, navigate to your Applications folder, and launch the Safari application. After it has finished starting up, enter, compile, and run the following script in a new script window in Script Editor.

Click to open example in the Script Editor application

Any open browser windows in the Safari application are immediately closed. As with the scripts you used with the Finder, note that this script is a tell statement containing the necessary two elements: a reference to the targeted objects (in this case the open browser windows) and the action to be performed (close).

Next, let’s use the open location command to open a Web page with the following script (assuming your computer is connected to the Internet).

A new browser window containing the specified Web site is displayed. Let’s see whether we can use the properties of the browser window to control where the window appears on the screen. Enter and run the following script to get the position coordinates of the new window.

Instead of getting a list of the horizontal and vertical offsets of the window, the Script Editor selects the word position and displays an error message in this dialog:

safari applescript commands

An error dialog displayed as a sheet attached to a script window in Script Editor.

The error message states (in a slightly convoluted way) that a script can’t refer to the position of a window in Safari. This is because, like many Mac OS X applications, Safari does not support the use of the position property for windows in the same manner as the Finder does. Instead, try using the bounds property to get the coordinates of the browser window. Enter and run this script:

Most scriptable Mac OS X applications support the bounds property for getting and setting window dimensions. You can use it to change the position and shape of the browser window. Try this script:

The Safari browser window is now sized and positioned to fit in the left section of the computer screen. Note that if you provide a vertical coordinate that is larger than the screen is tall, Safari automatically adjusts the vertical display of a browser window so that it doesn’t go below the Dock or the bottom of the screen. Very convenient.

So as you’ve now seen, you can use AppleScript to close, open, and resize Safari windows. And the point is?

The principles you learned scripting Finder windows apply to other scriptable applications and objects as well.

Just as the Finder application has scriptable window elements, so does the Safari application. And as with Finder windows, windows in Safari have properties that have corresponding values that can be read and sometimes changed. A browser window has a bounds property, just like a Finder window, whose value is a list of four numbers describing the location of its top-left corner and bottom-right corner on the screen.

TIP: If you’ve ever wanted to be able to make your browser window fill your computer’s display, here’s a script that uses the result of a tell statement that gets the bounds of the Finder Desktop to resize the frontmost Safari window to fill the screen:

You’ll learn more about how to pass information between script statements in Chapter 8, Data Containers, Operators, and Coercions .

Principles Remain Constant?

Let’s continue validating the universal nature of AppleScript principles. Navigate to the Applications folder, and open the QuickTime Player application.

Next, open a movie file by choosing Open Movie in New Player from the File menu and locating a movie file on your computer. Any standard QuickTime movie will do.

Like the Finder application, QuickTime Player contains other scriptable elements besides windows, one of which is the movie object. As with the scripts you wrote to query Finder windows, you can use the get verb to access the values of the properties of the scriptable objects or elements of QuickTime Player.

NOTE: The terms object and element are used interchangeably in describing scriptable items that belong to other scriptable items, such as Finder windows belonging to the Finder application or movie windows belonging to the QuickTime Player application.

NOTE: In QuickTime 7.2 the term movie was replaced by the term document , and any scripts written using movie will be changed when they are compiled. They will run the same, but the term document will appear instead of movie . For compatibility with Tiger, the term movie is used in these example scripts.

The result of the script is the value of the name property of a movie. Now, try this script:

The result of the script is the value of the duration property of a movie expressed as a number indicating the number of frames in the movie.

As with other scriptable applications, you can use the set verb to change the value of the property of an object. The following script changes the value of the current time property of a movie to move the playback cursor to a specified point in the movie.

QuickTime Player also responds to these commands for controlling the playback of movies:

The AppleScript principles that work with the Finder application work for the QuickTime Player application as well. Let’s try applying them to one more application.

Quit QuickTime Player without saving any changes, and open the iTunes application.

Like the other scriptable applications, iTunes contains scriptable elements or objects that contain other scriptable elements. If you are familiar with iTunes, you know the application has playlists , which are collections of tracks or songs. The master playlist for the application, containing all tracks, is the library playlist .

Here’s the basic object hierarchy for the iTunes application:

In other words, tracks are contained in playlists that are contained in the iTunes application.

As with the Finder and QuickTime Player applications, each one of the scriptable elements of iTunes has properties with corresponding values. Let’s try accessing some of the properties of the track object with the tell statement shown in the follwoing script:

Remember, a tell statement has two components: a reference to the target object and the action to be performed. In this example, the target object is the last track of the first library playlist , and the action to be performed is to get the value of its name property.

Now extract the value of other track properties using the following script:

As these examples demonstrate, playlists contain tracks that have properties, such as name , duration , artist , album , and so on.

The iTunes application, like the Finder and QuickTime Player, responds to AppleScript commands to perform actions with its scriptable objects. See, for example, the following script:

In this example, the verb play is used to initiate the playing of the track referenced as its target. To stop the iTunes application, use the stop verb. It doesn’t require a reference to a particular track because it targets the iTunes application, which only one track can play at a time.

What’s Next?

Congratulations on completing your introduction to the world of AppleScript. As you’ve seen, it’s an easy but powerful way to control the actions of applications.

If you’ve understood the concepts presented in this chapter, you’re well on your way to becoming a powerful scripter, because the lessons presented here will be used to create even more interesting and useful automation tools.

In the next chapter, you’ll discover how to access all of the scriptable objects, properties, and commands of any scriptable application by reading its terminology dictionary. See you there !

TOP | CONTINUE

  • The First Step
  • Properties and Values
  • The Script Editor
  • The Name Property
  • The Index Property
  • The Target Property
  • The Toolbar Visible Property
  • The Statusbar Visible Property
  • The Sidebar Width Property
  • The Current View Property
  • The Position Property
  • The Bounds Property
  • Verbs Used with Windows
  • The Desktop Setup Script
  • The Tell Block
  • Nested Tell Blocks
  • Saving the Setup Script
  • Chapter Review

Using AppleScript to open a URL in Private Browsing in Safari

  • Posted 24 June 2020
  • Tagged with applescript , macos , macos:safari

I have a bunch of automations that open URLs.

If I want to open a regular window in Safari (my default browser), I have a variety of options – I can use open(1) on the command-line, or the webbrowser module in Python, or with AppleScript, or probably half a dozen other methods I haven’t thought of.

If I want to open a private browsing window, my options are more limited. The Safari AppleScript dictionary doesn’t know about private browsing, and all the other approaches I’ve seen are just passing Safari the URL to open. They can’t give it any instructions beyond “please open this URL”.

If you ask Google, there are lots of suggestions, but I struggled to find good code. Many of the results are broken, slow, or incomplete (they open the private browsing window, but not any URLs).

Rather than wade through more Google results, I came up with my own script for doing it, which opens the window and the URL:

I save this as a script in my $PATH and mark it as executable, and then I can open a new private browsing window from anywhere by running:

When you run this code, you may get an error (or a silent failure if you trigger it through a GUI rather than a terminal):

open_private_browsing:114:232: execution error: System Events got an error: osascript is not allowed assistive access. (-1719)

This is the macOS security system kicking in: it doesn’t let arbitrary scripts or applications click menu items in other applications. To allow this script to work, open the Security & Privacy preference pane. Under Accessibility , allow access to whatever application is triggering the script (in my case, iTerm 2), and it should be good.

applescript

  • Getting started with applescript
  • AppleScript Browser Interactions
  • Applescript from the Terminal command line
  • Get the current URL in Safari or Google Chrome
  • Get the Title of the current page in Safari or Google Chrome
  • Use an Applescript as a shell function
  • AppleScript User Interaction
  • AppleScript Variable Types
  • Making Applescript If and Else Statements

applescript Applescript from the Terminal command line

Fastest entity framework extensions, introduction.

Applescript is a powerful scripting language that can be used directly from the Terminal command line to accomplish a multitude of tasks.

All examples listed in this section are meant to be used from the Terminal application.

Applescript from the Terminal command line Related Examples

Got any applescript question.

pdf

  • Advertise with us
  • Cookie Policy
  • Privacy Policy

Get monthly updates about new articles, cheatsheets, and tricks.

Documentation Archive

safari applescript commands

Mac Automation Scripting Guide

safari applescript commands

Navigating Script Editor Documents

Targeting a scripting language, viewing script events and results, getting to know script editor.

image: ../Art/script-editor_icon_2x.png

Script Editor, found in /Applications/Utilities/ , is an app for writing AppleScripts and JavaScripts. It provides the ability to edit, compile, and run scripts, browse scripting terminology, and save scripts in a variety of formats including compiled scripts, apps, and plain text.

A Script Editor document window includes the following main areas, as shown in Figure 5-1 :

image: ../Art/script-editor_window_withcallouts_2x.png

Toolbar —Use this to compile, run, and stop your script. Buttons are also available for showing and hiding the accessory view pane and the bundle contents pane. Select View > Customize Toolbar, or Control-click on the toolbar and choose Customize Toolbar, to choose what buttons displayed in the toolbar.

The toolbar also includes a Record button, which converts manual mouse clicks and keystrokes into script code. However, recording is not supported in JavaScript and few apps support AppleScript recording.

Navigation bar —Use this bar to select a scripting language, target an app, or navigate through the handlers in your script.

The navigation bar currently only supports navigation of AppleScript handlers.

Editor pane —Write your script code here.

Accessory View pane —View and edit your script’s description here, or browse the result and events produced when your script runs.

Bundle Contents pane — Edit the identifier, version, and copyright info for your script here. You can also use this pane to add, remove, or manage resources contained within the bundle. This pane is accessible only when your script is saved in script bundle or app format.

When you create a Script Editor document, select a scripting language in the navigation bar. See Figure 5-2 .

image: ../Art/script-editor_langage_selector_2x.png

If you always use the same language, set it as the default in the General pane of Script Editor preferences. See Figure 5-3 .

image: ../Art/script-editor_preferences_window_general_pane_language_2x.png

Script Editor can display the result of executing a script, as well as a log of events sent and received during execution.

Viewing the Script Result

The result of executing your script—if a result was produced—is found in the Accessory View pane. See Figure 5-4 .

image: ../Art/script-editor_window_result_2x.png

Do one of the following:

Press Command-2.

Choose View > Show Result.

image: ../Art/icon_showresult_2x.png

Viewing the Script Log

The Accessory View pane also contains a script log. See Figure 5-5 .

image: ../Art/script-editor_eventlog_2x.png

The script log displays the following information.

Result —The result of executing your script.

Messages —Includes log messages generated as your script runs, as well as the script’s result.

Events —Includes log messages, the script’s result, and events—commands—sent to applications.

Replies —Includes log messages, the script’s result, events sent to applications, and event replies.

Press Command-3.

Choose View > Show Log.

image: ../Art/icon_showlog_2x.png

Viewing the Log History

The result and script log areas in the Accessory View pane reset each time you run your script. However, you can view historical logs for an opened script in the Log History window. See Figure 5-6 .

image: ../Art/script-editor_resulthistory_window_2x.png

Press Option-Command-L.

Choose View > Log History.

image: ../Art/icon_loghistory_2x.png

About this Guide

Creating a Script

Copyright © 2018 Apple Inc. All rights reserved. Terms of Use | Privacy Policy | Updated: 2016-06-13

Sending feedback…

We’re sorry, an error has occurred..

Please try submitting your feedback later.

Thank you for providing feedback!

Your input helps improve our developer documentation.

How helpful is this document?

How can we improve this document.

* Required information

To submit a product bug or enhancement request, please visit the Bug Reporter page.

Please read Apple's Unsolicited Idea Submission Policy before you send us your feedback.

Script Editor User Guide

  • About Script Editor
  • Choose a script language
  • Edit scripts
  • Add commands using the shortcut menu
  • Find text in a script
  • View script results
  • Record actions
  • Save a compiled script
  • Run a script
  • Skip forward to an element using the navigation bar
  • Set up the Log History
  • Track events
  • Save a script as an app
  • Identify script file types
  • Change Script Editor settings
  • Access scripts using the Script menu
  • Set line wrapping
  • View an app’s scripting dictionary
  • Add or remove apps from the scripting dictionary
  • Automate Script Editor tasks
  • Keyboard shortcuts

safari applescript commands

View an app’s scripting dictionary in Script Editor on Mac

An app’s scripting dictionary displays the scripting vocabulary understood by an app or a scripting addition.

To find out what commands and objects you can use to control an app, use Script Editor to look at that app’s dictionary. The scripting dictionary of an app is organized into different suites. Most scriptable apps contain at least the standard suite. Other apps may have a variety of different suites of objects and commands available. An app’s dictionary may contain multiple languages—for example an app’s dictionary may include both AppleScript and JavaScript for Automation.

Open Script Editor for me

Double-click the name of the app in the Library window.

Click the Language pop-up menu, then choose a scripting language.

Select a suite.

If a scriptable app doesn’t appear in the library, see Add or remove apps from the scripting dictionary .

IMAGES

  1. The Ultimate Beginner's Guide To AppleScript

    safari applescript commands

  2. Apple: Applescript

    safari applescript commands

  3. Using AppleScript to record the Safari browser windows and tabs

    safari applescript commands

  4. Apple: AppleScript : Execute JavaScript on every Safari Tab/Window (2 Solutions!!)

    safari applescript commands

  5. Apple: How to Identify Safari Javascript Alert Dialog using AppleScript

    safari applescript commands

  6. Generate a List of Open Safari Tabs With AppleScript

    safari applescript commands

VIDEO

  1. Safari Shortcuts in Mac

  2. Voice commands on Tata Safari #tata #safari #trending #shorts #alexa #viral

  3. AppleScript: Safari (Webautomation)

  4. The Bateleur Eagle

  5. Switch Control+AppleScript Demo (Safari 4)

  6. Easyfreesurfer

COMMENTS

  1. macos

    Yes, there is a simple way. Open the Script Editor app (formerly called AppleScript Editor) Go to File -> Open Dictionary. Select the app you want to find out more about. When you open it, you can browse through the available AppleScript commands for that application and find what you want. Share. Improve this answer. edited Oct 4, 2019 at 1:35.

  2. Commands Reference

    Commands Reference. This chapter describes the commands available to perform actions in AppleScript scripts. For information on how commands work, see Commands Overview.. The commands described in this chapter are available to any script—they are either built into the AppleScript language or added to it through the standard scripting additions (described in Scripting Additions).

  3. Introduction to AppleScript Language Guide

    This document is a guide to the AppleScript language—its lexical conventions, syntax, keywords, and other elements. It is intended primarily for use with AppleScript 2.0 or later and macOS version 10.5 or later. AppleScript 2.0 can use scripts developed for any version of AppleScript from 1.1 through 1.10.7, any scripting addition created for ...

  4. Automate tasks using AppleScript and Terminal on Mac

    In the Finder on your Mac, open the /Applications/Utilities folder.. Drag the Terminal app icon onto the Script Editor app icon .. Open Terminal's AppleScript dictionary for me. In AppleScript, you can use the Do Shell Script command to send a UNIX shell script command to Terminal.

  5. Mac Automation Scripting Guide: Automating the User Interface

    Open in Script Editor. Listing 37-1AppleScript: Targeting an app for user interface scripting. tell application "System Events". tell process "Safari". -- Perform user interface scripting tasks. end tell. end tell. To control the user interface of an app, you must first inspect the app and determine its element hierarchy.

  6. How to open a new window and multiple urls in Safari with apple script?

    The way to create a new window in Safari is to use the make new document command:. make new document at end of documents with properties {URL:the_url} This will create a new window with a single tab pointing to the_url and make that window frontmost. Note that make new window at end of windows doesn't work, and just errors out with "AppleEvent handler fails".

  7. Generate a List of Open Safari Tabs With AppleScript

    The syntax for counting the windows is super straightforward: set (variable) to number of windows. AppleScript's commands are often very close to plain English, making it a really easy language for beginners to pick up quickly. ... I found the specific syntax for these commands in the Safari AppleScript dictionary. Notice that, to grab the name ...

  8. How to use AppleScript in macOS

    To save an AppleScript, press Command-S on the keyboard, enter a name, select a File Format from the popup menu, and click the "Save" button. The Save panel.

  9. Script Editor User Guide for Mac

    How to save a script as an app. To explore the Script Editor User Guide, click Table of Contents at the top of the page, or enter a word or phrase in the search field. Learn how to use Script Editor on your Mac to create tools, apps, and scripts that perform repetitive tasks, automate workflows, and more.

  10. AppleScript: Beginner's Tutorial

    In a new Finder window, navigate to your Applications folder, and launch the Safari application. After it has finished starting up, enter, compile, and run the following script in a new script window in Script Editor. ... The iTunes application, like the Finder and QuickTime Player, responds to AppleScript commands to perform actions with its ...

  11. Using AppleScript to open a URL in Private Browsing in Safari

    Tagged with applescript, macos, macos:safari; I have a bunch of automations that open URLs. If I want to open a regular window in Safari (my default browser), I have a variety of options - I can use open(1) on the command-line, or the webbrowser module in Python, or with AppleScript, or probably half a dozen other methods I haven't thought of.

  12. applescript Tutorial => Applescript from the Terminal command line

    Applescript from the Terminal command line Related Examples. Get the current URL in Safari or Google Chrome ; Get the Title of the current page in Safari or Google Chrome ; Use an Applescript as a shell function ; Got any applescript Question? Ask any applescript Questions and Get Instant Answers from ChatGPT AI:

  13. Mac Automation Scripting Guide: Getting to Know Script Editor

    For example, executing the make command to create a folder in the Finder produces the newly created folder object as its result. The result of a script is the result of the script's last statement. ... In AppleScript, log messages are generated using the log command. See Listing 5-1. APPLESCRIPT. Open in Script Editor. Listing 5-1AppleScript: ...

  14. View an app's scripting dictionary in Script Editor on Mac

    Double-click the name of the app in the Library window. Click the Language pop-up menu, then choose a scripting language. Select a suite. If a scriptable app doesn't appear in the library, see Add or remove apps from the scripting dictionary. In Script Editor on your Mac, view the dictionary of commands an app understands.

  15. An AppleScript for Safari: Split Tabs to New Window

    Command-Space to bring up LaunchBar, type "spl" to select this script, hit Return, done. Worth a warning though: "moving" tabs with this script doesn't actually move them like drag-and-drop does. The tabs "moved" by this script will reload in the new window, so you'll lose (a) the current scroll position, and, more dangerously ...

  16. safari

    1. Working on a AppleScript that opens a webpage in Safari and makes a screen capture of a specific area (using Cmd+Shift+4). But I'm having trouble making the screen capture part automatic. I'm using MouseTools to click and move the mouse around. set x to POSIX file ((POSIX path of (path to me)) & "/.." & "/MouseTools") as text. set pathName ...