Skip to content

Instantly share code, notes, and snippets.

@kevinold
Forked from aleks-mariusz/safari-open-pages.py
Created September 29, 2023 16:33
Show Gist options
  • Save kevinold/5dd7448b8e28ca3325f3a8b8b949f2e5 to your computer and use it in GitHub Desktop.
Save kevinold/5dd7448b8e28ca3325f3a8b8b949f2e5 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)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment