Skip to content

Instantly share code, notes, and snippets.

@kch
Created July 3, 2010 23:16
Show Gist options
  • Save kch/462919 to your computer and use it in GitHub Desktop.
Save kch/462919 to your computer and use it in GitHub Desktop.
Copies the URLs from all tabs in Safari/WebKit's front window to the pasteboard.
#!/usr/bin/env ruby
# encoding: UTF-8
require 'rubygems'
require 'appscript'
include Appscript
# Copy Window's URLs:
# Copies the URLs from all tabs in Safari/WebKit's front window to the pasteboard.
# `process_for_either_browser` will be any process named Safari, this includes
# both the standard Safari process and the WebKit process as well. If both
# Safari and Webkit are running, the process that was first started wins.
#
# Unfortuatelly, when both browsers are running, it's impossible to tell which
# is frontmost. Asking either process will return the same answer, which,
# again, relates to the one that was started first.
#
# If neither browser is running (`process_for_either_browser.exists`), we'll
# try the name_of_default_browser. Notice that we have not resolved it yet.
# Shelling out to perl is expensive, especially on the first run. So we wrap
# the code in a lambda and only call it when actually needed.
VALID_BROWSERS = %w[ WebKit Safari ]
process_for_either_browser = app("System Events").processes['Safari']
name_of_default_browser = lambda { %x<VERSIONER_PERL_PREFER_32_BIT=yes /usr/bin/perl -MMac::InternetConfig -le 'print +(GetICHelper "http")[1]'>.chomp }
name_of_target_application = process_for_either_browser.exists ? process_for_either_browser.short_name.get : name_of_default_browser.call
raise "No valid browser found" unless VALID_BROWSERS.include? name_of_target_application
browser_app = app(name_of_target_application)
urls_from_front_window = browser_app.windows.first.tabs.get.map{ |tab| tab.URL.get }.join("\n")
IO::popen('pbcopy', 'w+') { |io| io.write urls_from_front_window }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment