Search current Safari selection on wikipedia etc.

Alec Jacobson

August 21, 2009

weblog/

I love SafariSIA, but to shave even more seconds off a search query I've made the following applescript which uses the current selection on the current safari page and searches that as a query on wikipedia (or whatever site you'd like to change it to):

-- some pieces adapted from
-- http://scriptbuilders.net/files/safariselectiontoscripteditordebugger1.0.1.html

-- If Safari isn't running, notify and terminate.
tell application "System Events"
	if (exists process "Safari") is false then
		display dialog "Safari isn't running. The script will now terminate." buttons ¬
			{"OK"} default button 1 with icon 0
		return
	end if
end tell

tell application "Safari"
	-- If no document, notify and terminate.
	if (exists document 1) is false then
		display dialog "No Safari document was found. The script will now terminate." buttons ¬
			{"OK"} default button 1 with icon 0
		return
	end if
	
	-- Attempt to get the selected text. Notify and terminate if no selection.
	try
		set selected_text to (do JavaScript "getSelection()" in document 1) as string
		if selected_text is "" then
			error
		end if
	on error
		-- Advise user to copy and paste text into new script document 'cause somethin' failed.
		set selected_text to text returned of (display dialog "Safari was unable to obtain the selected text. Copy and paste " & ¬
			"it into the new document which has been created in Script Editor." buttons ¬
			{"OK"} default answer "" default button 1 with icon 1)
		
	end try
	
	-- construct url with selected text as query
	set theURL to "http://www.wikipedia.org/search-redirect.php?search=" & selected_text & "&language=en&go=++%3E++&go=Go"
	make new document at end of documents with properties {URL:theURL}
end tell
Change the set theURL to ... line to whatever site you'd like to search. For example: Google Images:
set theURL to  "http://images.google.com/images?q="&theURL&"&hl=en&btnG=Search+Images"
Google Maps:
http://maps.google.com/maps?client=safari&rls=en&q="&theURL&"&oe=UTF-8&um=1&ie=UTF-8&sa=N&hl=en&tab=wl
English to spanish dictionary look up on WordReference:
set theURL to  "http://www.wordreference.com/es/translation.asp?tranword="&theURL
Mininova (sorted by number of seeds):
set theURL to "http://www.mininova.org/search/"&theURL&"/seeds"