Skip to content

Instantly share code, notes, and snippets.

@marlonklc
Last active April 30, 2023 02:41
Show Gist options
  • Save marlonklc/4adad7dad5e677e121f4c17a0a2503e0 to your computer and use it in GitHub Desktop.
Save marlonklc/4adad7dad5e677e121f4c17a0a2503e0 to your computer and use it in GitHub Desktop.
youtube auto translate subtitles using google translator API

This is a simple script which copy subtitles when you are watching youtube videos on web browsers.

PS: This "gist" is the same situation that I described before to solve a simple problem that I went trought. See more on link: https://gist.github.com/marlonklc/ad1647cc52e1ca02d22ce74cbd565760

Updated (24/05/22)
I have improved this script to that is possible show a popup to auto translate the subtitles, using google translator API. So that way you don't need change tabs or go to site for translate the text.

How do I run this?

  1. First thing you need to enable subtitles, like show on result image.
  2. Configures what source and target language (need to pass this properties to google translator) on script above (0-youtube-subtitles-script.js) by SOURCE_LANGUAGE and TARGET_LANGUAGE variables.
  3. Copy the final script (editable for you) and paste this script after the command javascript: <script> on browser url bar and press enter. Example below: image
  4. After step three, you will look a button that copy the subtitles and show a popup on left side with text translated.

PS: Let's feel free to copy or improve it, or left your comment. Cheers!

Result

image

const SOURCE_LANGUAGE = "en";
const TARGET_LANGUAGE = "pt-br";
const button = document.createElement('button');
button.textContent = 'copy and translate';
button.addEventListener('click', () => {
const subtitleElement = document.getElementsByClassName('captions-text')[0];
const selectedTexts = Array.from(subtitleElement.children)
.map(i => i.children[0])
.map(i => i.innerHTML.replace('<br>', '').replace('&nbsp;', ''))
.join(' ');
navigator.clipboard.writeText(selectedTexts);
const url = `https://translate.googleapis.com/translate_a/single?client=gtx&sl=${SOURCE_LANGUAGE}&tl=${TARGET_LANGUAGE}&dt=t&dt=bd&dj=1&q=${selectedTexts}`;
fetch(url, { method: 'POST' })
.then(async function(response) {
const res = await response.json();
const translatedText = res.sentences[0].trans;
console.log(translatedText);
const div = document.createElement('div');
div.innerHTML = translatedText;
div.style = 'z-index:9999;position:absolute;bottom:0;left:0.5%;width:40%;height:8%;font-size:1.8em;background:#efefef;border:1px solid #000;';
document.body.appendChild(div);
setTimeout(() => { div.remove(); }, 5000);
});
});
button.style = 'position:absolute;bottom:0;right:42.5%;width:15%;height:8%;font-size:2.2em;background:#0398fc;';
document.body.appendChild(button);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment