walls.corpus

By Nathan L. Walls

Saving Safari URLs with AppleScript and Ruby

I occasionally have a metric mumbleton of browser windows and tabs open, particularly if I’m digging into a research topic. In the past, if I’ve needed to close out windows or tabs, but have wanted to keep the context, I’ve gone to each tab individually and saved the URL to a file.

In the last week, I found myself with about five windows and 45 tabs, so my typical approach strikes me as insufficiently lazy. So, I was going to find or write something to handle the task for me. My initial Google research didn’t turn up the sort of AppleScripts I fully expected to exist. So, it looked like I was going to be writing AppleScript myself.

I found some code in a similar area and I reached my typical wall with AppleScript. At some point, I should actually solve a problem with AppleScript, but instead, I used the rb-appscript gem and wrote a Ruby script that interacted with the Safari AppleScript dictionary, based on a concept I saw in a StackOverflow post.

Here it is:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#!/usr/bin/env ruby

require 'appscript'
require 'yaml'

include Appscript

safari    = app 'Safari'
url_list  = safari.windows.tabs.URL.get

url_list.flatten!

dt          = DateTime.now
date_format = dt.strftime("%F_%H%M")
list_path   = "#{ENV['HOME']}/saved_urls_#{date_format}.yml"

File.open(list_path, "w") do |f|
  f.puts(url_list.to_yaml)
end

This is also available as a syntax-highlighted GitHub Gist.

It’s nothing magic, but just the sort of simple utility that solves a small problem for me.