Last active
January 20, 2020 03:57
-
-
Save drzhbe/9d8c1a9f73254855e2d3 to your computer and use it in GitHub Desktop.
Click on english word to translate it into russian. Translation will be logged into console.
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
/** | |
* <a href='http://api.yandex.ru/dictionary/'>Реализовано с помощью сервиса «API «Яндекс.Словарь»</a> | |
*/ | |
(function() { | |
const YANDEX_DICTIONARY_KEY = 'dict.1.1.20150130T172350Z.0895b15babe24c90.431f35fa9af476be1b6d14d80f3809ab693a5970'; | |
const DICTIONARY_URL = `https://dictionary.yandex.net/api/v1/dicservice.json/lookup?key=${YANDEX_DICTIONARY_KEY}&lang=en-ru` | |
function translate(word) { | |
fetch(`${DICTIONARY_URL}&text=${word}`) | |
.then(res => res.json()) | |
.then(data => { | |
if (!data.def.length && | |
word[word.length-1] === 's' && | |
word[word.length-2] !== 's') | |
{ | |
// yandex.dictionary is really bad with plurals, so cut "s" ending and try again | |
word = word.substr(0, word.length-1); | |
translate(word); | |
return; | |
} | |
const translation = data.def[0] && | |
data.def[0].tr && | |
data.def[0].tr[0] && | |
data.def[0].tr[0].text; | |
const translatedStyle = 'color: #c55'; | |
console.log('%s — %c%s', word, translatedStyle, translation); | |
}); | |
} | |
document.addEventListener('click', evt => { | |
const selection = window.getSelection(); | |
selection.modify('move', 'backward', 'word'); | |
selection.modify('extend', 'forward', 'word'); | |
const word = selection.toString(); | |
translate(word); | |
}); | |
})(); |
Author
drzhbe
commented
Jan 31, 2015
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment