Hack #90. Translate Any Web Page

Add a form at the top of every web page to translate it into your language.

Google Language Tools offers automated online translation of any web page. It's simple to use; just visit http://translate.google.com, enter the URL of the page, and select the source and target languages.

As is the case with so many web services, it would be even simpler to use if it were integrated with the web pages you visit. This hack adds a form at the top of every web page to hook it into Google's translation service.

The Code

This user script runs on all pages. It contains a hardcoded matrix of all the translations that Google Language Tools can perform automatically. English dominates the lists, as both a source and a target language. The script attempts to autodiscover the page's language by looking for a lang attribute on the <html> element. In XHTML, authors can also specify the language in the xml:lang attribute, but that functionality is left as an exercise for the reader. In theory, authors can also specify the language in the Content-Language HTTP header, but HTTP headers are not accessible to user scripts, so we can't check for that either.

On the bright side, the script does remember your previous choices for source and target languages, using the GM_setValue and GM_getValue functions to store your preferences in the local Firefox preferences registry.

Save the following user script as translatepage.user.js:

 // ==UserScript== // @name Translate Page // @namespace ...

Get Greasemonkey Hacks now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.