Auto Translate to English

Automatically translate web pages to English

  1. // ==UserScript==
  2. // @name Auto Translate to English
  3. // @namespace https://discord.gg/VnxvMFbKbu
  4. // @version 0.2
  5. // @description Automatically translate web pages to English
  6. // @author Pixel.Pilot
  7. // @match http://*/*
  8. // @match https://*/*
  9. // @grant GM_xmlhttpRequest
  10. // @license You are not allowed to reuse this script for any purpose.
  11. // ==/UserScript==
  12. (function() {
  13. 'use strict';
  14.  
  15. function translateText(text, onSuccess, onError) {
  16. const url = `https://translate.googleapis.com/translate_a/single?client=gtx&sl=auto&tl=en&dt=t&q=${encodeURIComponent(text)}`;
  17. GM_xmlhttpRequest({
  18. method: 'GET',
  19. url: url,
  20. onload: function(response) {
  21. const jsonResponse = JSON.parse(response.responseText);
  22. const translatedText = jsonResponse[0][0][0];
  23. if (translatedText) {
  24. onSuccess(translatedText);
  25. } else {
  26. onError();
  27. }
  28. },
  29. onerror: function(error) {
  30. onError(error);
  31. }
  32. });
  33. }
  34.  
  35. function translateAllVisibleElements() {
  36. const allElements = document.querySelectorAll('*');
  37. allElements.forEach(element => {
  38. if (element.nodeType === Node.TEXT_NODE && element.parentElement.tagName !== 'SCRIPT') {
  39. translateText(element.textContent.trim(),
  40. translatedText => {
  41. element.textContent = translatedText;
  42. },
  43. () => {
  44. console.log(`Translation failed for: ${element.textContent}`);
  45. });
  46. } else if (element.hasChildNodes() && element.tagName !== 'SCRIPT') {
  47. translateAllVisibleElementsRecursive(element);
  48. }
  49. });
  50. }
  51.  
  52. function translateAllVisibleElementsRecursive(element) {
  53. element.childNodes.forEach(childNode => {
  54. if (childNode.nodeType === Node.TEXT_NODE && childNode.parentElement.tagName !== 'SCRIPT') {
  55. translateText(childNode.textContent.trim(),
  56. translatedText => {
  57. childNode.textContent = translatedText;
  58. },
  59. () => {
  60. console.log(`Translation failed for: ${childNode.textContent}`);
  61. });
  62. } else if (childNode.hasChildNodes() && childNode.tagName !== 'SCRIPT') {
  63. translateAllVisibleElementsRecursive(childNode);
  64. }
  65. });
  66. }
  67.  
  68. translateAllVisibleElements();
  69.  
  70. // Update Ideas:
  71. // 1. Language Detection
  72. // 2. User Interaction (Button/Menu)
  73. // 3. Customization (Select Target Language)
  74. // 4. Error Handling (Display Messages)
  75. // 5. Performance Optimization
  76. // 6. Exclude Elements
  77. // 7. Translation Cache
  78. // 8. Settings Panel
  79.  
  80. })();