Skip to content

Instantly share code, notes, and snippets.

@edenwaith
Last active January 7, 2024 13:01
Show Gist options
  • Star 18 You must be signed in to star a gist
  • Fork 5 You must be signed in to fork a gist
  • Save edenwaith/2213a764ccb091d6a03989f238efb63f to your computer and use it in GitHub Desktop.
Save edenwaith/2213a764ccb091d6a03989f238efb63f to your computer and use it in GitHub Desktop.
AppleScript: Count the number of open tabs in Safari
-- CountOpenSafariTabs.scpt
-- Author: Chad Armstrong
-- Date: 13 May 2016
-- Description: Count the number of open tabs in Safari
-- To run from CLI: osascript CountOpenSafariTabs.scpt
tell application "Safari"
--Variables
set winlist to every window
set totaltabcount to 0
-- Loop through each window to count the number of open tabs
repeat with win in winlist
try
set tabcount to number of tabs in win
set totaltabcount to totaltabcount + tabcount
-- log "tab count: " & tabcount & " totaltabcount: " & totaltabcount
on error errmsg
-- Often getting error message like this:
-- "Safari got an error: AppleEvent handler failed."
-- log "error message: " & errmsg
end try
end repeat
log "There are " & totaltabcount & " Safari tabs open."
end tell
@w0rthyw0rks
Copy link

@edenwaith great stuff, really appreciate it, been wrestling with getting a tab count script to work correctly. Your's works really well!

@sebma
Copy link

sebma commented Aug 1, 2017

@edenwaith Hi,

How can I run this from Safari ?

@gingerbeardman
Copy link

gingerbeardman commented Apr 9, 2018

@sebma see this: https://apple.stackexchange.com/questions/260540/how-to-install-user-applescripts-for-safari-and-activate-the-scripts-menu-item

an alternative method would be to install the script as a Service, so it's accessible from any app, including Safari

@ChristoferK
Copy link

A bit briefer and quicker:

tell application "Safari" to return the number of tabs in windows

@edenwaith
Copy link
Author

@ChristoferK Excellent suggestion. That's much simpler, cleaner, and noticeably faster version of the script.
A Google Chrome version of that script would be:
tell application "Google Chrome" to return the number of tabs in windows

@TomVerhoeven
Copy link

A bit briefer and quicker:

tell application "Safari" to return the number of tabs in windows

Thanks this works great!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment