Spotify Web Translator to English

Translate Spotify Web to English using DeepL

当前为 2024-08-05 提交的版本,查看 最新版本

  1. // ==UserScript==
  2. // @name Spotify Web Translator to English
  3. // @namespace http://tampermonkey.net/
  4. // @version 1.0
  5. // @description Translate Spotify Web to English using DeepL
  6. // @author Inari
  7. // @match https://open.spotify.com/*
  8. // @grant none
  9. // @icon https://www.google.com/s2/favicons?sz=64&domain=spotify.com
  10. // ==/UserScript==
  11.  
  12. (function() {
  13. 'use strict';
  14.  
  15. function waitForElement(selector, callback) {
  16. const observer = new MutationObserver((mutations) => {
  17. mutations.forEach((mutation) => {
  18. const element = document.querySelector(selector);
  19. if (element) {
  20. observer.disconnect();
  21. callback(element);
  22. }
  23. });
  24. });
  25.  
  26. observer.observe(document.body, { childList: true, subtree: true });
  27. }
  28.  
  29. function translateText(text, callback) {
  30. const deeplURL = `https://www.deepl.com/translator#auto/en/${encodeURIComponent(text)}`;
  31.  
  32. const iframe = document.createElement('iframe');
  33. iframe.style.display = 'none';
  34. iframe.src = deeplURL;
  35. document.body.appendChild(iframe);
  36.  
  37. iframe.onload = () => {
  38. setTimeout(() => {
  39. const translatedText = iframe.contentDocument.querySelector('.lmt__target_textarea').value;
  40. document.body.removeChild(iframe);
  41. callback(translatedText);
  42. }, 5000);
  43. };
  44. }
  45.  
  46. function translatePage() {
  47. const textNodes = [];
  48. const walker = document.createTreeWalker(document.body, NodeFilter.SHOW_TEXT, null, false);
  49.  
  50. let node;
  51. while (node = walker.nextNode()) {
  52. textNodes.push(node);
  53. }
  54.  
  55. textNodes.forEach((textNode) => {
  56. const originalText = textNode.nodeValue.trim();
  57. if (originalText) {
  58. translateText(originalText, (translatedText) => {
  59. textNode.nodeValue = translatedText;
  60. });
  61. }
  62. });
  63. }
  64.  
  65. translatePage();
  66.  
  67. waitForElement('.main-view-container__scroll-node', translatePage);
  68.  
  69. })();