Created
February 3, 2015 05:14
-
-
Save 1995eaton/a9111f9f077ea990d939 to your computer and use it in GitHub Desktop.
Google Translate script
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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