Skip to content

Instantly share code, notes, and snippets.

@chaityacshah
Forked from aleks-mariusz/safari-open-pages.py
Last active June 29, 2018 20:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chaityacshah/9906e69dcc4e0eaa8172b082207bf7fa to your computer and use it in GitHub Desktop.
Save chaityacshah/9906e69dcc4e0eaa8172b082207bf7fa 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
from pprint import pprint
# 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 range(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 range(1, result.descriptorAtIndex_(1).descriptorAtIndex_(page_idx).numberOfItems()+1 ) ]
tabs[win_num] = list(zip(urls,titles))
pprint(tabs)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment