Skip to content

Instantly share code, notes, and snippets.

@1995eaton
Created February 3, 2015 05:14
Show Gist options
  • Save 1995eaton/a9111f9f077ea990d939 to your computer and use it in GitHub Desktop.
Save 1995eaton/a9111f9f077ea990d939 to your computer and use it in GitHub Desktop.
Google Translate script
function translate(text, callback) {
var xhr = new XMLHttpRequest();
xhr.open('POST', 'https://www.google.com/async/translate?');
var data = 'async=translate,sl:auto,tl:en,st:' + encodeURIComponent(text) + ',id:0,_id:tw-async-translate,_pms:s';
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded;charset=utf-8');
xhr.onreadystatechange = function() {
if (xhr.readyState === 4 && xhr.status === 200) {
a = JSON.parse(xhr.responseText);
var doc = document.implementation.createHTMLDocument();
doc.body.innerHTML = JSON.parse(xhr.responseText)[1][1];
var translation = doc.querySelector('#tw-answ-target-text').textContent;
callback(translation);
}
};
xhr.send(data);
}
translate('これは、Google翻訳のためのテストです。', function(result) {
console.log('"%s"', result);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment