0

I want to get DeepL translation result by UserScript. The case is that I want to simulate user input by JavaScript, once the input got translated, I want to get the result from the result textarea with the class name lmt__target_textarea, I have tried the change event of the textarea, and also tried with the MutationObserver, but I still cannot get the result, any other ways?

My little UserScript demo as following(one can click the blank area to simulate user input, it is a bit weird, there is a different approach in real action):

// ==UserScript==
// @name        New script - deepl.com
// @namespace   Violentmonkey Scripts
// @match       https://www.deepl.com/*
// @grant       none
// @version     1.0
// @author      -
// @description 2022/10/24 下午1:23:45
// ==/UserScript==




document.addEventListener('click', (event) => {
  document.querySelector(".lmt__source_textarea").value ="测试一下在线翻译服务"
  document.querySelector(".lmt__source_textarea").dispatchEvent(new KeyboardEvent( 'keyup' , {'key':'Ctrl'} ));

});


document.querySelector('.lmt__target_textarea').addEventListener('input', (event) => {
    console.log(document.querySelector(".lmt__target_textarea").value);
});


var observer = new MutationObserver(function (mutationRecordList, observer) {//https://stackoverflow.com/a/61511955/1485853
  console.log(document.querySelector(".lmt__target_textarea").value);

  // socket = new WebSocket('ws://127.0.0.1:8522');
  // socket.onopen = function() {
  //     socket.send(document.querySelector(".lmt__target_textarea").value);
  // };
});

// observer.observe(document.querySelector('.lmt__target_textarea'), {subtree: true, attributes: true, childList: true, characterData : true});
observer.observe(document.querySelector('.lmt__target_textarea'), { attributes: true, childList: true, subtree: true,characterData: true});
iMath
  • 2,326
  • 2
  • 43
  • 75

1 Answers1

1

change target element to #target-dummydiv

document.addEventListener('click', (event) => {
  document.querySelector(".lmt__source_textarea").value ="测试一下在线翻译服务"
  document.querySelector(".lmt__source_textarea").dispatchEvent(new KeyboardEvent( 'keyup' , {'key':'Ctrl'} ));

});

document.querySelector('.lmt__target_textarea').addEventListener('input', (event) => {
    console.log(document.querySelector(".lmt__target_textarea").value);
});

// here
let targetElement = document.querySelector('#target-dummydiv');
var observer = new MutationObserver(function (mutationRecordList, observer){
  console.log(targetElement.textContent);
});

observer.observe(targetElement, { attributes: true, childList: true, subtree: true,characterData: true});
uingtea
  • 6,002
  • 2
  • 26
  • 40