From 0df0f2ef2023e8e63bfea3d926134d5c3a81b410 Mon Sep 17 00:00:00 2001 From: Gres Date: Sat, 4 Apr 2020 15:14:48 +0300 Subject: [PATCH] Added baidu translator --- translators/baidu.js | 42 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) create mode 100644 translators/baidu.js diff --git a/translators/baidu.js b/translators/baidu.js new file mode 100644 index 0000000..6996c0c --- /dev/null +++ b/translators/baidu.js @@ -0,0 +1,42 @@ +var lastText = ''; +var active = window.location.href !== "about:blank"; + +function checkFinished() { + if (!active) return; + + let spans = [].slice.call(document.querySelectorAll('p.target-output')); + let text = spans.reduce(function (res, i) { + return res + ' ' + i.innerText; + }, '').trim(); + + if (text === lastText || text === '') + return; + + console.log('translated text', text, 'old', lastText, 'size', text.length, lastText.length); + lastText = text; + active = false; + proxy.setTranslated(text); +} + +function translate(text, from, to) { + console.log('start translate', text, from, to) + active = true; + + let langs = from + '/' + to; + if (window.location.href.indexOf('//fanyi.baidu.com/') !== -1 + && window.location.href.indexOf(langs) !== -1) { + document.querySelector('textarea#baidu_translate_input').value = text; + document.querySelector('textarea#baidu_translate_input').dispatchEvent( + new Event("input", { bubbles: true, cancelable: true })); + return; + } + + let url = 'https://fanyi.baidu.com/#' + langs + '/' + encodeURIComponent(text); + console.log("setting url", url); + window.location = url; +} + +function init() { + proxy.translate.connect(translate); + setInterval(checkFinished, 300); +}