Small Google Chrome Inline translate extension

Today I noticed, that I often want to translate some text in Google Chrome but not the entire page. As you know, you can translate the entire page by clicking “Translate to …” in the context menu of Google Chrome. But if you want to translate just a single word or sentence you have to go to http://translate.google.com and enter the text.

So digged into the Google Chrome extension API and after a short amount of time I had my own little Inline Translate Extension, wich translates to german.
Here is the Code:

manifest.json

{
  "name": "Inline Translate",
  "version": "0.1",
  "description": "Translate selected Text with Google Translate.",
  "permissions": [
	"contextMenus",
	"https://www.googleapis.com/language/translate/",
	"notifications"
  ],
  "background_page": "background.html"
}

background.html

<script src="inlineTranslate.js"></script>

inlineTranslate.js

var API_KEY = "Your Google Translate API Key";

function translateSelection(info, tab) {
    var textToTranslate = escape(info["selectionText"]);
    var url = "https://www.googleapis.com/language/translate/v2?key=" + API_KEY + "&target=de&q=" + textToTranslate;
    var xhr = new XMLHttpRequest();

    xhr.open("GET", url, true);
    xhr.onreadystatechange = function () {
        if (xhr.readyState == 4) {
            var resp = JSON.parse(xhr.responseText);
            var translation = resp.data.translations[0]["translatedText"];

            if (translation.length > 0) {
                var notification = webkitNotifications.createNotification('', 'Translation result:', translation);
                notification.show();
                console.log(translation);
            }
        }
    }

    xhr.send();
}

var contextMenu = chrome.contextMenus.create({
    "title": "Translate",
    "contexts": ["selection"],
    "onclick": translateSelection
});

This was my first experience with Google Chrome extensions and I liked it 🙂

http://code.google.com/chrome/extensions/index.html

This entry was posted in Google Chrome, Javascript. Bookmark the permalink.