prettify

baseline

Google Translate using JSONP

We have a web page.
In this page there is a set of Fields (input-text/ textarea) with Greek (or whatever google supports) text content.
There are some corresponding Fields where we like to have the english translation.
First get a key from Google API console
You have to remember that max URL length is 2038 characters for IE, that gives less than 1K for the string to translate. You can get more (a lot) from chrome, firefox, opera (>64K).
Google says that you can to it with POST instead of GET, but that is another post.
Usage:
$("btnEn").onclick = ins.Translate($("txtGr"), $("txtEn"));
ins library:
var $=function(sId){return document.getElementById(sId);};
if (typeof ins !== "object") { var ins = {}; }
ins.Translator = function (eLangFr, eLangTo, sKey, eFormat) {
  var that = this;
  var MAX_LENGTH = 2072;
  this.oCbs = {};
  this.nCounter = 0;
  this.base = "https://www.googleapis.com/language/translate/v2?" +
    "key="+ sKey +
    "&source=" + eLangFr+
    "&target=" + eLangTo;
  this.nTimeOut = 200000;
  this.send = function (sText, callback) {
    var sId = "cb" + (++this.nCounter);
    var url = this.base+
      "&callback=oTrn.oCbs." + sId+
      "&q=" + encodeURIComponent(sText); //escape(sText)
    if (url.length > MAX_LENGTH) {
      alert("Length is: " + url.length.toString() + "\n" + "Max is: 2072");
    }

    var oScr = document.createElement("script");
    var oTo = setTimeout(
      function () { 
        cleanup(sId, oScr); 
        callback(null); 
      }, 
      this.nTimeOut
    );
    var cleanup = function (sId0, oScr0) { 
      delete oTrn.oCbs[sId0]; 
      setTimeout(function (){document.body.removeChild(oScr0);},0)};
      this.oCbs[sId] = function (oResponse) {
        clearTimeout(oTo);
        delete this[sId];
        document.body.removeChild(oScr);
        callback(oResponse);
      };
      oScr.type = "text/javascript";
      oScr.src = url;
      document.body.appendChild(oScr);
  };
};
var oTrn = new ins.Translator("el", "en",MY_GOOGLE_KEY, "text"); //html
ins.Translate = function (oFr, oTo) {
  return function () {
    oTrn.send(oFr.value, function (oResponse) { 
      oTo.value = oResponse.data.translations[0].translatedText; 
    });
  };
};

No comments:

Post a Comment