DEV Community

wimdenherder
wimdenherder

Posted on • Updated on

Translate and read out loud the selection on your page

Update: at the bottom you'll find the Chrome extension

In two previous posts I discovered two very accessible api's that you can use nowadays:

  1. a free translate google endpoint here
  2. the speech api available in the browser here

Let's combine these and create a script that reads out your selection in another language. Great for language learning!

Open up the developer console and copy paste the two functions from the previous posts:

function speak(text, language) {
  const synth = window.speechSynthesis;
  const utterance = new SpeechSynthesisUtterance(text);
  utterance.voice = synth
    .getVoices()
    .find(
      (voice) =>
        voice.lang.split("-")[0].toLowerCase() ===
        language.split("-")[0].toLowerCase()
    );
  synth.speak(utterance);
}

async function translate(text, source, target) {
  const response = await fetch(`https://translate.googleapis.com/translate_a/single?client=gtx&hl=en-US&dt=qca&dt=t&dt=bd&dj=1&source=icon&sl=${source}&tl=${target}&q=${text}`);
  const json = await response.json();
  return json.sentences.map(x => x.trans).join(" ");
}
Enter fullscreen mode Exit fullscreen mode

Now we should obtain the selected text on the page. I copied the next from this stackoverflow post

function getSelectionText() {
  var text = "";
  var activeEl = document.activeElement;
  var activeElTagName = activeEl ? activeEl.tagName.toLowerCase() : null;
  if (
    activeElTagName == "textarea" ||
    (activeElTagName == "input" &&
      /^(?:text|search|password|tel|url)$/i.test(activeEl.type) &&
      typeof activeEl.selectionStart == "number")
  ) {
    text = activeEl.value.slice(activeEl.selectionStart, activeEl.selectionEnd);
  } else if (window.getSelection) {
    text = window.getSelection().toString();
  }
  return text;
}
Enter fullscreen mode Exit fullscreen mode

Now we can combine it into this function. We want to trigger the function everytime you select text on the page. We use the mouseup event and check if there is a selection. Change the targetLanguage below as you wish (See list of codes here)

config = {
  targetLanguage: "es",
};

async function translateAndReadSelection(language) {
  const text = getSelectionText().replace(/\n+/g, " ");
  if (!text) return;
  const translated = await translate(text, "auto", language);
  console.log("reading the page contents in language " + language, translated);
  speak(translated, language);
}

document.onmouseup = () =>
translateAndReadSelection(config.targetLanguage);
Enter fullscreen mode Exit fullscreen mode

Enjoy!

You can find the Chrome Extension and try it out here:
Chrome Extension: Flippify

Top comments (0)