On a typical day, I might have a dozen Safari windows open, each replete with its own set of tabs. With each tab sandboxed in its own process, this can result in a bevy of running tasks on the system. As an interesting (and useful) exercise, I wanted to write a small script which would quickly tell me how many open tabs I had in Safari.
The most obvious solution for my needs to be able to interact with Mac applications, yet retain the flexibility of a programming language is AppleScript. AppleScript is just another one of a multitude of languages I've dabbled with over the years, going as far back as the System 7 days. I pick up AppleScript every now and again when the appropriate need arises, but I find myself needing to relearn its capabilities. AppleScript has high readability with its English-like syntax, but it makes for some esoteric writing at times, to ensure that the proper syntax is being used.
The goal is straightforward: Grab every Safari window, total up the number of tabs, and return the result. In this particular example, I had the script print out the result so I could run it from the command line using the
The Code for Safari
Running the script
$ osascript CountOpenSafariTabs.scpt There are 112 Safari tabs open.
To further simplify things, I added the following alias to my
.bash_profile file, so I only need to type
counttabs in the Terminal to get the desired answer:
alias counttabs='osascript ~/Projects/scripts/CountOpenSafariTabs.scpt'
The Code for Chrome
2 December 2019 Update: The following is a similar AppleScript for Google Chrome.