Advertisement
Zero_G

DeepL - Auto VN Translation Extension Helper (Fixed)

Feb 3rd, 2023 (edited)
1,339
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // ==UserScript==
  2. // @name         DeepL - Auto VN Translation Extension Helper
  3. // @version      1.1
  4. // @grant        GM.setClipboard
  5. // @match        https://www.deepl.com/translator
  6. // @description  Watch for target language element class change, copy new value of textarea to clipboard each time change has been detected.
  7. // @author       Zero_G
  8. // @icon         https://www.deepl.com/img/logo/deepl-logo-blue.svg
  9. // ==/UserScript==
  10. (function() {
  11.     'use strict';
  12.     // Filters to apply to translated text
  13.     const filters = {
  14.       '' : /\"+|\'\'+/g,        // Remove " or ''
  15.       '...' : /\.\.\.\.+/g      // Change multiple dots (when there are more than 3 to '...' only)
  16.     }
  17.  
  18.     const mutationObserver = new MutationObserver(callback)
  19.  
  20.     // Observe the text div that contains the translation
  21.     // But as the translated text appears in a <p> in a ::before css we need to watch
  22.     // for added nodes
  23.     mutationObserver.observe(
  24.         document.getElementsByClassName('lmt__target_textarea')[0].lastChild, {
  25.             childList: true
  26.         }
  27.     )
  28.  
  29.     function callback(mutationsList) {
  30.         mutationsList.forEach(mutation => {
  31.             if (mutation.type === 'childList' && // Irrelevant as we are already watching for childList only but meh
  32.                 mutation.addedNodes.length !== 0 && // Looking for a mutation with an added node
  33.                 mutation.removedNodes.length !== 0 && // This condition is to prevent a repeat
  34.                 !mutation.addedNodes[0].innerHTML.includes('<br')) { // Filter out garbage while translating
  35.                 // Get text from <p>
  36.                 let text = mutation.addedNodes[0].innerHTML;
  37.                
  38.                 // Apply filters
  39.                 for (const [key, value] of Object.entries(filters)) {
  40.                   text = text.replace(value, key);
  41.                 }
  42.              
  43.                 // Copy to memory with GreaseMonkey special function (needs @grant)
  44.                 GM.setClipboard(text);
  45.             }
  46.         })
  47.     }
  48. })();
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement