Skip to content

Instantly share code, notes, and snippets.

@aleks-mariusz
Created August 24, 2014 16:35
Show Gist options
  • Star 12 You must be signed in to star a gist
  • Fork 6 You must be signed in to fork a gist
  • Save aleks-mariusz/cc27b21f2c5b91fbd285 to your computer and use it in GitHub Desktop.
Save aleks-mariusz/cc27b21f2c5b91fbd285 to your computer and use it in GitHub Desktop.
This script fetches the current open tabs in all Safari windows. Useful to run remotely on your mac when you are at work and want to read a page you have open (remotely) at home but don't remember the url but can log in to your home system on the command line
#!/usr/bin/python
#
# This script fetches the current open tabs in all Safari windows.
# Useful to run remotely on your mac when you are at work and want
# to read a page you have open (remotely) at home but don't remember
# the url but can log in to your home system on the cmmand line
#
import sys
# work around needed for if not using the system python (such as with anaconda python distrib)
#mod_path = '/System/Library/Frameworks/Python.framework/Versions/{0:}.{1:}/Extras/lib/python/PyObjC'.format( sys.version_info[0], sys.version_info[1] )
#sys.path.append(mod_path)
from Foundation import NSAppleScript
# create applescript code object
s = NSAppleScript.alloc().initWithSource_(
'tell app "Safari" to {URL,name} of tabs of windows'
)
# execute AS obj, get return value
result,_ = s.executeAndReturnError_(None)
# since we said {URL,name} we should have two items
assert result.numberOfItems() == 2
# find number of tabs based on number of groups in the URL set
num_windows = result.descriptorAtIndex_(1).numberOfItems()
# create a simple dictionary
tabs = dict(( 'window {0:}'.format(win_num), []) for win_num in range(1, num_windows+1) )
for page_idx,win_num in enumerate(tabs,start=1):
urls = [ result.descriptorAtIndex_(1).descriptorAtIndex_(page_idx).descriptorAtIndex_(tab_num).stringValue()
for tab_num in xrange(1, result.descriptorAtIndex_(1).descriptorAtIndex_(page_idx).numberOfItems()+1 ) ]
titles = [ result.descriptorAtIndex_(2).descriptorAtIndex_(page_idx).descriptorAtIndex_(tab_num).stringValue().encode('ascii','xmlcharrefreplace')
for tab_num in xrange(1, result.descriptorAtIndex_(1).descriptorAtIndex_(page_idx).numberOfItems()+1 ) ]
tabs[win_num] = zip(urls,titles)
from pprint import pprint
pprint(tabs)
@ZenBerry
Copy link

ZenBerry commented Oct 4, 2018

Thanks a lot! Also works with Chrome if 'tell app "Chrome" to {URL,name} of tabs of windows'

@mmagnus
Copy link

mmagnus commented Mar 8, 2022

After so many years still works! just explicitly I had to use python2.

(base) ➜  d python2 safari-open-pages.py
{'window 1': [(u'http://rna.bgsu.edu....

thanks @aleks-mariusz

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