Created
August 24, 2014 16:35
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
After so many years still works! just explicitly I had to use python2.
thanks @aleks-mariusz