This seems like it should have been done before, but I couldn’t find it anywhere so I just wrote a solution from scratch. Basically the subroutine accepts a big ugly block of text containing one or more plain text URLs, and returns a clean list of all the URLs it found. The following script gives an example of how the handler can be used to pop up a list of URLs. Double-clicking one will launch it in your default client for the web, mail, chat, ftp, etc.
Important Considerations:
- The script as written assumes that the URLs you’re looking for begin with a common URI scheme, and end with a space. You can correct for this if necessary, by changing the values for “endDelim” and “URISchemes”
- The script as written returns the URLs sorted first by their URI scheme, and then by the order that they appear in the text.
set myText to "http://zombo.com This is a bunch of ugly text with URLs littered in it
http://bbs.applescript.net/viewtopic.php?id=13333 yadda yadda
yadda http://www.macscripter.net/ yadda yadda yadda mailto:John@doe.com yadda yadda
yadda yadda http://www.yahoo.com yadda yadda
yadda yadda http://apple.com/applescript
ftp://ftp.gimp.org/
aim:JohnDoe"
set theURL to choose from list getURLs(myText)
open location theURL
on getURLs(sourceText)
set endDelim to " " (* change this value if you're looking for
something other than a space at the end of your URLs *)
set URLList to {}
set oldDelims to AppleScript's text item delimiters
set AppleScript's text item delimiters to "
" -- strip carriage returns
set sourceText to text items of sourceText
set AppleScript's text item delimiters to endDelim
set sourceText to sourceText & endDelim as string
set URISchemes to {"http:", "https:", "file:", "ftp:", "mailto:", "aim:", "telnet:", "news:", "rtsp:", "afp:", "eppc:", "rss:"}
repeat with delim from 1 to length of URISchemes
set delim to item delim of URISchemes as string
set AppleScript's text item delimiters to delim
set trimText to {}
repeat with x from 2 to length of sourceText's text items
set trimText to trimText & (text item x of sourceText) as list
end repeat
set AppleScript's text item delimiters to endDelim
repeat with x from 1 to length of trimText
set URLList to URLList & (delim & text item 1 of item x of trimText) as list
end repeat
end repeat
set AppleScript's text item delimiters to oldDelims
return URLList
end getURLs
Feel free to let us all know if you can break this subroutine, or make it more efficient…