Skip to content

Instantly share code, notes, and snippets.

@Quantalabs
Last active May 11, 2025 02:14
Show Gist options
  • Select an option

  • Save Quantalabs/6e9b2ab1688e6c28df9d2fbd6adb7bf1 to your computer and use it in GitHub Desktop.

Select an option

Save Quantalabs/6e9b2ab1688e6c28df9d2fbd6adb7bf1 to your computer and use it in GitHub Desktop.
A simple bookmarklet to translate text on webpages

Languagelet

A simple bookmarklet to translate text on webpages.

Use

Use the following snippet:

javascript:(async function () {
  try {
    const sel = window.getSelection();
    if (!sel || sel.rangeCount === 0) {
      alert("Please select some text to translate.");
      return;
    }

    const tl = prompt("Translate to which language? (e.g., fr, es, en)", "en");
    if (!tl) return;

    for (let i = 0; i < sel.rangeCount; i++) {
      const range = sel.getRangeAt(i);
      const text = range.toString().trim();
      if (!text) continue;

      const res = await fetch(
        `https://translate.googleapis.com/translate_a/single?client=gtx&sl=auto&tl=${encodeURIComponent(tl)}&dt=t&q=${encodeURIComponent(text)}`
      ).then(r => r.json());

      const translated = res[0].map(seg => seg[0]).join("");

      range.deleteContents();
      range.insertNode(document.createTextNode(translated));
    }
  } catch (err) {
    console.error("Translation error:", err);
    alert("There was an error translating the text.");
  }
})();

Or, drag this link to your bookmarks bar.

  1. Select the text you want to translate.
  2. Run the bookmarklet, which will send the selected text through a Google Translate API for translation
  3. Text will be replaced with translated version (may take some time).
async function () {
try {
const sel = window.getSelection();
if (!sel || sel.rangeCount === 0) {
alert("Please select some text to translate.");
return;
}
const tl = prompt("Translate to which language? (e.g., fr, es, en)", "en");
if (!tl) return;
for (let i = 0; i < sel.rangeCount; i++) {
const range = sel.getRangeAt(i);
const text = range.toString().trim();
if (!text) continue;
const res = await fetch(
`https://translate.googleapis.com/translate_a/single?client=gtx&sl=auto&tl=${encodeURIComponent(tl)}&dt=t&q=${encodeURIComponent(text)}`
).then(r => r.json());
const translated = res[0].map(seg => seg[0]).join("");
range.deleteContents();
range.insertNode(document.createTextNode(translated));
}
} catch (err) {
console.error("Translation error:", err);
alert("There was an error translating the text.");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment