Looks like no one’s replied in a while. To start the conversation again, simply ask a new question.

max.p

Applescript to open URL in Safari without titlebar...almost working :-)

iMac, MacBook Pro, Mac OS X (10.6.4)

Posted on Aug 30, 2010 8:37 AM

Chachi

Posted on Aug 30, 2010 3:04 PM

Loading page content

Page content loaded

Aug 30, 2010 3:04 PM in response to max.p

Aug 30, 2010 3:13 PM in response to Chachi

Aug 30, 2010 3:25 PM in response to max.p

Aug 31, 2010 11:35 AM in response to Chachi

alvin alexander

AppleScript Safari URL tip: How to open multiple URLs in Safari tabs

Well, I set out to write a simple tip on how to activate a Mac application using AppleScript, and I ended up writing a program to open a list of URLs in separate tabs in Safari using AppleScript. (Yeesh, I really took a detour. Oh, well.)

Without any further ado, here's the source code for this AppleScript program:

Brief description of the code

Here's a brief description of what this AppleScript program does:

  • urlList is a simple list with the URLs I want Safari to open.
  • The repeat statement starts the loop.
  • I'm clicking File :: New Tab using the System Events because I can't figure out how to get this to work by calling Safari directly. (I'm currently using Safari 3.0.3.)
  • The keystroke command types the URL into Safari.
  • key code 36 is needed to hit the [Enter] key.

Again, I had to take a few extra steps here because I couldn't script the tabs in Safari directly. Ideally code like this would have worked inside the tell application "Safari" statement:

Hopefully that support will be available in the future, or, if I'm mistaken, please send me an email and I will correct this program.

Help keep this website running!

  • How to open a macOS Terminal in the current Finder folder
  • AppleScript tip: script a program that isn't scriptable
  • AppleScript tip: if/then syntax
  • Mac OS X Finder FAQ: How to open the Finder from a Terminal window
  • Mac AppleScript Finder: How to put the path of the current Finder window on the clipboard

books by alvin

  • Ram Dass’s Grist for the Mill
  • Dropping Keys, by Hafez
  • Coldplay’s Chris Martin: “So happy to be alive”
  • Listen with ears of tolerance, see through eyes of compassion
  • Rumi: My religion is love

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.

  • Google Nest Wi-Fi Pro 6E is $60 off
  • The best laptops for 2024
  • YouTube prevents ad-blocking mobile apps
  • Best Mint alternative

Use AppleScript to open current Safari URL in Google Chrome

I've been using John Gruber's suggestions from Going Flash-Free on Mac OS X, and How to Cheat When You Need It to avoid installing Adobe Flash by using Google Chrome (which includes its own version of Flash) whenever I run into a page that has Flash I want to see.

To make this easier, John suggested turning on the "Develop menu" in Safari's "Advanced" preferences, which includes a sub-menu to "Open Page With" and a sub-sub-menu that shows all of your installed browsers. John suggested using System Preferences to create a keyboard shortcut for "Google Chrome" or "Google Chrome.app" depending on which one you saw in the menu.

Unfortunately, this failed for me quite often. Every time I launched Safari, the keyboard shortcut would not work until I had opened that menu manually using the mouse. I hate using the mouse. After opening the menu, the keyboard shortcut would work until I quit Safari again. That was mildly annoying, but things recently took a turn for the worse.

Here's what the menu looks like for me now:

Notice that the browser listings now include version numbers. This means that a keyboard shortcut would have to include the version number, which means it would break whenever the browser is updated.

I asked a few folks, and it appears this changed in Safari 5.0.4. I haven't been able to find a way to revert to the old behavior, so I started looking for another way.

Enter AppleScript

Using AppleScript, you can send the current URL from Safari to Google Chrome.

Here is the AppleScript that I am currently using:

(Note: this article was updated on 2013–02–10 to include an updated and improved version of the AppleScript, as well as expanded instructions on how to use it.)

This AppleScript will launch Google Chrome if it is not already running, and will not overwrite any existing tabs in Google Chrome.

To use this AppleScript, you will need to download it from Github . Note that the download filename will be something ridiculously long which starts with 'gist4750810' (don't ask me why, it's a Github 'thing'). Find that file in your Downloads folder, double-click it, and Archive Utility will open it and show you a folder with a file named 'Open in Google Chrome.scpt' in it.

Now you'll want to open a new Finder window so you can navigate to where that file needs to be installed, so choose File » New Finder Window and then move on to the next section.

Installation

To use 'Open in Google Chrome.scpt' in Safari, it needs to be installed to ~/Library/Scripts/Applications/Safari/ (where ~ is the path to your Home directory).

If that folder does not exist, you will need to create it. The easiest way to do this is to go to the Finder and then choose the "Go to Folder..." option from the Go menu, as shown here:

Once you have done that, a window will appear prompting you to enter the path that you want to go to. Enter

~/Library/Scripts/Applications/Safari/

and see if it opens the folder.

(Aside: If it says "The folder can't be found" try going to ~/Library/Scripts/Applications/ instead, and then just create the 'Safari' folder using File » New Folder from the menu bar.)

Once you are in the ~/Library/Scripts/Applications/Safari/ folder, simply drag the 'Open in Google Chrome.scpt' file to it from the other Finder window.

Using 'Open in Google Chrome.scpt' From Safari

Once 'Open in Google Chrome' is installed, there are two ways to use it from Safari.

Option one is to use the "Scripts" menu extra from OS X. Option two is to use a program called FastScripts . I prefer FastScripts, but will explain how to use the standard OS X option first.

To use that Scripts menu, launch the "AppleScript Editor.app" found in /Applications/Utilities/ and then go to Preferences and enable the option 'Show Script menu in menu bar' as shown here:

Once the Script menu is enabled, you will see 'Open in Google Chrome' whenever you are in Safari. Just click on the Scripts icon in the menu bar and select it as shown here:

But what if you want to use a keyboard shortcut instead of the mouse? For that you will need FastScripts , which gives you everything the standard 'Scripts' menu offers, plus the ability to assign keyboard shortcuts.

To assign a keyboard shortcut, open FastScript's preferences and find the entry for 'Safari' under your home folder, then locate the 'Open in Google Chrome' entry. Click over in the 'Shortcut' column and assign it a keyboard shortcut. As you can see here, I have chosen ⌥ (Option) + G :

FastScripts lets you assign up to 10 keyboard shortcuts for AppleScripts for free. If you want to use more than 10, you'll need to buy a license for US$15. As a keyboard-lovin' mouse-hater, I consider that a bargain. FastScripts offers a lot more than just keyboard shortcuts , so I would encourage you to check it out.

"Flash Free"

Now whenever I am in Safari and encounter a page which requires Flash, I press ⌥ + G and the page loads in Google Chrome. It's quick and easy, and doesn't require that I maintain a separate Flash installation.

Adobe Flash continues to be a source of security problems. Using it in only Google Chrome is a good way to increase your browsing security, especially since Chrome is frequently updated.

p.s. since I know there are many other Keyboard Maestro fans out there, I'll also add a quick link to my Keyboard Maestro macro for doing this same thing using Keyboard Maestro.

Latest Stories

The best foldable phones for 2024.

Here are the best foldable phones you can get right now, from Samsung and Google handsets to everything in between.

Take-Two plans to lay off 5 percent of its employees by the end of 2024

Take-Two Interactive plans to lay off 5 percent of its workforce, or about 600 employees, by the end of the year.

NASA confirms its space trash pierced Florida man’s roof

On March 8, a piece of space debris plunged through a roof in Naples, FL, ripped through two floors and (fortunately) barely missed the son of homeowner Alejandro Otero. On Tuesday, NASA confirmed the results of its analysis of the incident.

Boston Dynamics sends Atlas to the robot retirement home

Boston Dynamics is retiring its dancing, search-and-rescue robot Atlas.

Ooni's largest pizza oven yet offers dual-zone heat control and temperature tracking on your phone

Ooni's largest pizza oven yet can accommodate a 20-inch pie. It also offers dual-zone cooking, upgraded gas burners and Bluetooth connectivity.

Get an Echo Pop speaker with a free TP-Link smart light bulb for only $23

An Amazon Echo Pop smart speaker is now down to $23 and comes with a smart bulb thrown in for free.

Amazon debuts a generative AI-powered playlist feature

Amazon Music has announced a generative AI-powered playlist feature. Enter a prompt (which can include emoji) and Maestro will try to find songs that match it.

Uber will start reminding passengers to wear their seat belt

Starting today, the Uber app will remind you to put on your seatbelt shortly after your ride starts.

Nintendo’s next Indie World showcase is set for April 17

Nintendo has announced an Indie World showcase for April 17. Might it finally, at long last be time for Hollow Knight: Silksong news?

The Kasa Smart Plugs Mini EP25 four-pack is down to its lowest price yet

The four-pack of Kasa Smart Plugs Mini EP25 four-pack is down to $32.50 thanks to a discount and added coupon.

Google Nest Wi-Fi Pro 6E packs are up to $60 off

Thanks to our exclusive discount code, you can save on a two-pack or three-pack of Google Nest Wi-Fi Pro 6E routers.

Insta360’s X4 captures 8K 360-degree video

Insta360's new action camera improves on 2022's X3 in every way, with substantial battery improvements, higher-resolution video and even more tricks.

YouTube prevents ad-blocking mobile apps from accessing its videos

The Google-owned video platform has announced that it's "strengthening [its] enforcement on third-party apps that violate" its Terms of Service, "specifically ad-blocking apps."

The best budgeting apps for 2024

Budgeting apps can help you keep track of your finances, stick to a spending plan and reach your money goals. These are the best budget-tracking apps available right now.

Motorola’s Edge 50 phone series includes a wood option

Motorola has announced its next generation Edge smartphones.

The Morning After: Samsung is, once again, shipping the most phones in the world

The biggest news stories this morning: Threads is testing real-time search results Tesla is reportedly laying off more than 10 percent of its workforce, Keanu Reeves’ latest iconic role is Shadow the Hedgehog.

Meta’s Oversight Board will rule on AI-generated sexual images

Meta's Oversight Board has accepted two cases that deal with AI-made explicit images of public figures.

The best smartwatches for 2024

Here’s a list of the best smartwatches you can buy, plus advice on how to choose one.

Netflix true crime documentary may have used AI-generated images of a real person

Netflix has been accused of using AI-manipulated imagery in the true crime documentary 'What Jennifer Did.'

Keanu Reeves is reportedly playing Shadow the Hedgehog in Sonic 3

Keanu Reeves will play the broody, tortured Shadow the Hedgehog, according to The Hollywood Reporter and Variety.

Stack Exchange Network

Stack Exchange network consists of 183 Q&A communities including Stack Overflow , the largest, most trusted online community for developers to learn, share their knowledge, and build their careers.

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

AppleScript use Safari window ID to create new tabs

I have an AppleScript that creates a new Safari document, then opens multiple URLs in that window using a repeat loop. I would like the script to continue using the same window even if it's not the frontmost window.

(The problem is that if a user changes focus to another Safari window this script will open the URLs in the frontmost window instead of the previously created window.)

I would like to solve this issue by using the window id if possible but need some help on the scripting.

To that end I have created the following but again I think there might be an issue. I would rather not get the id using front window since a user could change the front window at an inopportune time and the script would pull the wrong window ID.

I would rather use something like

Even using the above I have been unable to open URLs in a window by using it's window id and need help with that scripting as well.

It would function something like this:

  • applescript

John's user avatar

  • 1 Just an FYI.. I've modified the example AppleScript code in my answer to use the window id directly and avoid using the index property of the window . –  user3439894 Aug 24, 2020 at 5:50

2 Answers 2

Update to address concerns of the use of: front window.

The following example AppleScript code guarantees the list of URL s gets opened in the target window regardless of its position in the z-order of windows .

Note: Scroll as needed to see all the code .

The updated example AppleScript code includes some error handling , in that if the tmp file (value of the tmpFileName variable ) is not created the script aborts without any message. This can be changed by converting the if not my writeToFile ... statement to a full if block and include an appropriate display alert , display dialog or display notification command , as wanted, followed by the return command .

As coded, this renders --> document "Untitled" returned from the make new document irrelevant, because with the included repeat loop it waits until the HTML file is loaded and can be queried by the actual name of the document as defined by the <title>" & windowName & "</title> tags in the document and ensures that the z-order is irrelevant.

The repeat loop as coded is written to wait up to 3 seconds for the HTML file to load and should be more than enough time. Adjust if necessary.

I opted to forgo the use of the do shell script command as used in your answer, however, if you prefer to use it, then:

Then remove the on writeToFile(theData, theFile, overwriteExistingContent) handler from the -- # Handler # section of the code .

Additionally, if you prefer a do shell script command to remove the tmp file , the value of the tmpFileName variable , then:

Original Answer

The following example AppleScript code is an example of how to open a list of URLs in the same window of Safari , regardless of its window order.

  • Do not use open location as it's a part of Standard Additions , not Safari . Use the URL property to set the URL of the document or tab .
  • Use a list of URLs and the index of the list item ( URL ) in the list .
  • When Safari is instructed to make new document , the new document becomes the front window of Safari . Get the window id of the front window immediately after the make new document command .
  • For subsequent URLs in the list , start the repeat loop at 2 and use the window id which was ascertained directly after the make new document command was executed.

user3439894's user avatar

  • Is there a way to do this so the newly created window has a location, front or back, and also has bounds? –  John Apr 13, 2021 at 17:39
  • @John, For changing the position/size of the window you can use the bounds command after the set winID to id of front window command , e.g., set bounds of window id winID to {0, 23, 1024, 768} . However, setting the position of the window , the value of the index of the window is not so straightforward, as it can depend on how many windows and what position you want to move the front window to. –  user3439894 Apr 13, 2021 at 19:51
  • @John, Have a look at this answer , you can take the lines of code from within the tell application "Finder" block and use that code to move the newly created window to the back of the z-order . You could add it after the. set winID to id of front window command or the, e.g., set bounds of window id winID to {0, 23, 1024, 768} command . –  user3439894 Apr 13, 2021 at 19:51

@user3439894 I accepted your answer - it answers the question well. There is another way - a hackie way to create an ID for a Safari window.

This allows the following commands to avoid using "front window" in case the window that was created is no longer frontmost when the rest of the commands begin - doubtful, but possible.

I am not sure there is a way to give a new window anything other than "Untitled" as a name while creating the window.

  • 1 John, Please see the Update to address concerns of the use of: front window section of my updated answer. Borrowing the concept from your answer I incorporated it into a fully functioning update of my original answer. Thanks. –  user3439894 Apr 14, 2021 at 18:53

You must log in to answer this question.

Not the answer you're looking for browse other questions tagged safari applescript ..

  • The Overflow Blog
  • How to succeed as a data engineer without the burnout
  • How do you evaluate an LLM? Try an LLM.
  • Featured on Meta
  • New Focus Styles & Updated Styling for Button Groups
  • Upcoming initiatives on Stack Overflow and across the Stack Exchange network
  • Google Cloud will be Sponsoring Super User SE

Hot Network Questions

  • Why do protests happen in the light of their apparent futility?
  • What is the provenance of this photo of the Great Lakes from space?
  • Can a Venus-like planet be habitable if it was farther from the sun?
  • Has Trump's political views changed on Israel's war in Gaza?
  • Rotational spectroscopy of diatomic molecules
  • What is this circuit? (FM detector?) - LTspice
  • Fitting a disk in a non-polygonal region
  • Why don't airports use different radio frequencies/channels for each plane to prevent communications from interfering with each other?
  • How to create grep output in the order of the input file?
  • Short story; a journalist visits a hospital with patients who are mentally ill. One patient pretends to use invisible tools to build a machine
  • What happens if the US President-elect is sent to prison before assuming power?
  • Would medieval humans know if an ancient civilization had existed and been wiped out?
  • What are some good examples of spectral sequences which degenerate after the first nontrivial differential?
  • Prepositions after, before etc. as temporal determiners
  • Situation with Artemov's paper?
  • Is a new Tourney rear hub better than a 15 year old Deore hub?
  • NASB translation of John 4:1
  • Michael Noll's early computer art - arranging graphic elements in a circular manner
  • Converting "4.8 million" into an actual number
  • Password checker using Decorator Pattern
  • Cryptic Acrostic 7: An Ode to "Mr. Malaprop"
  • Where does "excess" energy go when a vehicle uses a lower gear to move at a given speed?
  • How to select an editor?
  • Can somebody other than the copyright holder enforce the GPL "inherited" by a project? Do they have to?

applescript open safari url

  • Home New Posts Forum List Trending New Threads New Media Spy
  • WikiPost Latest summaries Watched WikiPosts
  • Support FAQ and Rules Contact Us

macOS   Applescript + Safari open URL

  • Thread starter Iceman332k1
  • Start date May 14, 2010
  • Sort by reaction score
  • Apple Programming

Iceman332k1

Macrumors newbie.

  • May 14, 2010

I need to make an Applescript that opens Safari (or switches to it if it's already open) and then opens a webpage. Just something basic like http://www.hulu.com or http://www.gmail.com . I want to bind it to a tap on my new magic mouse, but for the life of me I am unable to find a script online that I can get to work. Again, I do not need it to do anything after opening the webpage. Thanks  

chown33

Code: tell application "Safari" to open location "http://www.hulu.com/"  

Confused I'm sorry, but could you type it out as it should read as an applet? I'm honestly having trouble and this is my first attempt at applescripts  

TuffLuffJimmy

TuffLuffJimmy

Macrumors g3.

  • May 15, 2010

Open AppleScript Utility (It's somewhere in the Applications folder I believe). Type the previous code with hulu.com replaced with whatever URL you want to go to. Save it as an Application. Now you have an Application. Double click the application to go to the URL.  

  • Aug 16, 2012

Reply If you don't want it to always open in safari, you can just remove the "tell application safari part" Make sure the browser you want to open it in is your default browser. Then in AppleScript, type: Code: open location "www.google.com" You can change the url to whatever you want. Then press "command shift s" to save as and select application. Now when you open the app, the url will open. Hope this helps!  

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 .

Sponsored Content

article thumbnail

Clean junk files from your Mac with Intego Washing Machine X9

Top stories.

article thumbnail

Apple's iOS 18 AI will be on-device preserving privacy, and not server-side

article thumbnail

How iOS Web Distribution works in the EU in iOS 17.5

article thumbnail

iPhone 16 Pro 256GB rumor makes sense, but is by a known falsifier

article thumbnail

Apple is researching how to make the ultimate MagSafe wallet and iPhone carrying case

article thumbnail

When to expect every Mac to get the AI-based M4 processor

Featured deals.

article thumbnail

Lowest price: Apple's M3 MacBook Air 16GB RAM, 512GB SSD, 10C GPU drops to $1,349

Latest comparisons.

article thumbnail

M3 15-inch MacBook Air vs M3 14-inch MacBook Pro — Ultimate buyer's guide

article thumbnail

M3 MacBook Air vs M1 MacBook Air — Compared

article thumbnail

M3 MacBook Air vs M2 MacBook Air — Compared

Latest news.

article thumbnail

How to organize Safari tabs using tab groups in iPadOS 17

Safari tab groups have been in iPadOS for several years, and can really help you organize pages you've browsed. Here's how to use them in iPadOS 17.

author image

Fear of Nintendo's wrath is keeping emulators off of the App Store

Despite Apple's recent rule change, it has been a bumpy few days for emulators on the App Store as small developers fear the wrath of Nintendo and others.

author image

Jerusalem Flag autoprediction bug is fixed in iOS 17.5 developer beta

Apple's second iOS 17.5 developer beta has fixed a bug that showed the Palestinian flag in the predictive text system when users typed in "Jerusalem."

author image

Apple rolls out second beta round, including EU Web Distribution in iOS 17.5

Apple has shifted onto the second round of developer betas, with the latest iteration of iOS 17.5 including Apple's Web Distribution system.

article thumbnail

Second developer beta of visionOS 1.2 has arrived

Owners of the Apple Vision Pro can now test out the second developer build of the visionOS 1.2 operating system.

article thumbnail

The new iOS 17.5 beta introduces app sideloading from websites in the EU and Apple has announced both what eligible developers have to do, and what users can expect to see.

author image

Apple will reportedly update its entire Mac line to the M4 processor, beginning in late 2024 and concluding with the Mac Pro in the second half of 2025.

article thumbnail

Future Apple Vision Pro could help the user get life-saving medical advice

Apple is developing technology for wearable devices like Apple Vision Pro that measure and monitor biometric data and location to provide tailored and potentially lifesaving advice.

author image

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.

article thumbnail

macOS Sonoma update fixes USB hubs, Java crashes, and more

Following iOS and iPadOS updates late last week, Apple has released a complementary update to macOS Sonoma with security updates and some big bug fixes.

article thumbnail

How to use Apple's Time Capsule for backups on a modern wireless network

Time Capsule was Apple's discontinued line of network backup products. This is how you could use one on a modern network.

Latest Videos

article thumbnail

The best game controllers for iPhone, iPad, Mac, and Apple TV

article thumbnail

How to get the best video capture possible on iPhone 15 Pro with ProRes

Latest reviews.

article thumbnail

Ugreen DXP8800 Plus network attached storage review: Good hardware, beta software

article thumbnail

Espresso 17 Pro review: Magnetic & modular portable Mac monitor

article thumbnail

Journey Loc8 MagSafe Finder Wallet review: an all-in-one Find My wallet

article thumbnail

{{ title }}

{{ summary }}

author image

IMAGES

  1. Apple: AppleScript URL from open safari window

    applescript open safari url

  2. AppleScript で Safari を開く

    applescript open safari url

  3. AppleScript で Safari を開く

    applescript open safari url

  4. AppleScript App Using Safari Interface

    applescript open safari url

  5. Apple: AppleScript application as a Safari Webpage

    applescript open safari url

  6. Generate a List of Open Safari Tabs With AppleScript

    applescript open safari url

VIDEO

  1. Drag & drop a Safari URL

  2. 【CVE-2015-3755】Apple Safari URL And Javascript Prompt Origin Spoof Vulnerability

  3. AppleScript: Safari (Webautomation)

  4. Как открыть ссылку в новой вкладке iPhone Safari

  5. How to change the home page in Safari

  6. Speech Recognition For Mac Tutorial 2

COMMENTS

  1. Open URL in new Safari tab with AppleScript

    tell application "Safari" try display dialog "Website URL" default answer "" buttons {"OK", "Annuler"} default button 1 set theURL to text returned of result set netProto to "https://" if theURL contains netProto then set the URL of (make new tab in window 1) to theURL else set the URL of (make new tab in window 1) to netProto & theURL end if ...

  2. How to open a specific url in the current Safari tab with AppleScript

    To open a URL in a tab in Safari, you use set url to and then the URL. So, for example, this script will open stack overflow in the current tab of the current window: tell application "Safari". tell window 1. tell current tab. set URL to "https://stackoverflow.com". end tell. end tell. end tell.

  3. Applescript to open URL in Safari without…

    tell application "Safari" activate set theURL to URL of document 1 set windowID to id of window 1 do JavaScript ("window.open('" & theURL & "','_blank','titlebar=0');") in document 1 close window id windowID end tell </pre> The above script opens a new window with the current document's url and then closes the original window.

  4. AppleScript to prompt for url input, open url in safari, then open

    I'd like the script to ask for the user to enter a url, it will then open a new window with this page and then it will click the bookmark which will itself run some JavaScript on the open page. The example AppleScript code , shown below, was tested in Script Editor under macOS Catalina with Language & Region settings in System Preferences set ...

  5. AppleScript Safari URL tip: How to open multiple URLs in Safari tabs

    tell application "System Events". -- enter the url in the open window. keystroke (item 1 of urlList) key code 36. repeat with i from 2 to (numURLs) -- for each additional url, first create a tab. tell process "Safari". click menu item "New Tab" of menu "File" of menu bar 1. end tell.

  6. 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.

  7. AppleScript, JavaScript and Safari Tabs

    In AppleScript, you can tell Safari to execute JavaScript and return a value. The JavaScript loops through all the links on the page and saves the ones that contain "newpost." The last line of the JavaScript, links;, returns the list to AppleScript. Then we tell Safari to make a new tab and load the URL for each of the links in the returned ...

  8. Use AppleScript to open current Safari URL in Google Chrome

    Using 'Open in Google Chrome.scpt' From Safari Once 'Open in Google Chrome' is installed, there are two ways to use it from Safari. Option one is to use the "Scripts" menu extra from OS X. Option ...

  9. Generate a List of Open Safari Tabs With AppleScript

    The syntax of these is nearly identical, only one grabs the name of the current tab and the other grabs the URL. I found the specific syntax for these commands in the Safari AppleScript dictionary. Notice that, to grab the name and URL of the current tab, we're simply using the x and y variables that increment each time the repeat block is run.

  10. AppleScript use Safari window ID to create new tabs

    The following example AppleScript code is an example of how to open a list of URLs in the same window of Safari, regardless of its window order. Notes: Do not use open location as it's a part of Standard Additions, not Safari. Use the URL property to set the URL of the document or tab. Use a list of URLs and the index of the list item (URL) in ...

  11. Applescript + Safari open URL

    Make sure the browser you want to open it in is your default browser. Then in AppleScript, type: Code: open location "www.google.com". You can change the url to whatever you want. Then press "command shift s" to save as and select application. Now when you open the app, the url will open. Hope this helps!

  12. How to use AppleScript in macOS

    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 ...

  13. Applescript that tells Safari to open a URL in my clipboard

    Skip to main content. Open menu Open navigation Go to Reddit Home. r/applescript A chip A close button A chip A close button

  14. Bad AppleScript: Safari and curling URLs

    We're building the command that we'll execute using do shell script, bit by bit. set shellScript to declares the shellScript variable we're building. ("curl --url is the command that will ...

  15. Open a new Safari Window on MacOS with AppleScript without messing

    @user3579815 try this: Start Safari. Resize the window. Close Safari. Open Safari. The new window should have your resized dimensions. Now try this: Start Safari. Resize the window. Open a new window. Resize to default size you want. Close that window. Close Safari. Open Safari. The new window should have your new default dimensions. -