Skip to content

Instantly share code, notes, and snippets.

@crmne
Last active May 15, 2018 18:06
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save crmne/8478027 to your computer and use it in GitHub Desktop.
Save crmne/8478027 to your computer and use it in GitHub Desktop.
UPDATE: I made a LaunchBar 6 action that you can find here: http://static.paolino.me/GoogleTranslate.lbaction.zip. Make sure to enable Accessibility for LaunchBar, and "Allow Javascript from Apple Events" in Safari's Develop menu. -- Translates text using Google Translate in Safari. It gracefully handles large text, which is impossible with just…
on safari_is_ready(docNum, interval)
repeat
tell application "Safari"
try
do JavaScript "document.readyState" in document docNum
set readyState to result
set finishedLoading to (source of document docNum contains "</html>")
if finishedLoading and readyState is "Complete" then exit repeat
end try
end tell
delay interval -- don't consume too much cpu
end repeat
end safari_is_ready
on replace_chars(this_text, search_string, replacement_string)
set AppleScript's text item delimiters to the search_string
set the item_list to every text item of this_text
set AppleScript's text item delimiters to the replacement_string
set this_text to the item_list as string
set AppleScript's text item delimiters to ""
return this_text
end replace_chars
on javascript_quoted_form_of(theString)
set theQuotedString to replace_chars(theString, "'", "\\'")
set theQuotedString to replace_chars(theQuotedString, "&", "\\&")
set theQuotedString to replace_chars(theQuotedString, "
", "\\n")
set theQuotedString to replace_chars(theQuotedString, " ", "\\t")
return theQuotedString
end javascript_quoted_form_of
on handle_string(theString)
set docNum to 1
set interval to 0.1
set javascriptCode to "document.getElementById('source').innerText = '" & my javascript_quoted_form_of(theString) & "';"
tell application "Safari" to open location "http://translate.google.com/#auto/en/"
my safari_is_ready(docNum, interval)
tell application "Safari"
do JavaScript javascriptCode in document docNum
activate
end tell
end handle_string
@luokuning
Copy link

Hi there, thanks for the script. It seems I can't download the action via http://static.paolino.me/GoogleTranslate.lbaction.zip, system tell me that it unable to resolve host address 'static.paolino.me'.

@crmne
Copy link
Author

crmne commented Oct 21, 2017

@luokuning: fixed, thanks for pointing that out!

@andyspicer
Copy link

Bravo Carmine, Bravo. Thank you!

@dorian-grey
Copy link

This crashes my Launchbar! :(

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment