ScreenTranslator/translators/google.js

54 lines
1.5 KiB
JavaScript
Raw Normal View History

2020-02-21 00:45:53 +07:00
var lastText = '';
var active = window.location.href !== "about:blank";
2015-10-08 22:36:02 +07:00
2020-03-21 01:44:46 +07:00
function checkFinished() {
2020-02-21 00:45:53 +07:00
if (!active) return;
let spans = [].slice.call(document.querySelectorAll('span.VIiyi > span > span'));
2020-03-21 01:44:46 +07:00
let text = spans.reduce(function (res, i) {
2020-02-21 00:45:53 +07:00
return res + ' ' + i.innerText;
}, '');
if (text === lastText || text === '')
2017-07-22 00:24:53 +07:00
return;
2020-03-21 01:44:46 +07:00
console.log('translated text', text, 'old', lastText, 'size', text.length, lastText.length);
2020-02-21 00:45:53 +07:00
lastText = text;
active = false;
2020-03-21 01:44:46 +07:00
proxy.setTranslated(text);
2015-10-08 22:36:02 +07:00
}
2020-03-21 01:44:46 +07:00
function translate(text, from, to) {
2020-02-21 00:45:53 +07:00
console.log('start translate', text, from, to)
2021-01-05 21:03:11 +07:00
if (text.trim().length == 0) {
proxy.setTranslated('');
return;
}
2020-02-21 00:45:53 +07:00
active = true;
if (window.location.href.indexOf('//translate.google') !== -1
2020-03-21 01:44:46 +07:00
&& window.location.href.indexOf('&tl=' + to + '&') !== -1) {
2021-01-05 21:03:11 +07:00
var input = document.querySelector('textarea.er8xn');
if (input.value == text) {
console.log('using cached result');
lastText = '';
return;
}
input.value = text;
input.dispatchEvent(new Event("input", { bubbles: true, cancelable: true }));
2017-07-22 00:24:53 +07:00
return;
}
2020-04-03 22:38:59 +07:00
let url = 'https://translate.google.com/#view=home&op=translate&sl=auto&tl=' + to + '&text=' + encodeURIComponent(text);
2020-02-21 00:45:53 +07:00
console.log("setting url", url);
2020-04-03 22:38:59 +07:00
window.location = url;
2020-02-21 00:45:53 +07:00
2015-10-08 22:36:02 +07:00
}
2020-02-21 00:45:53 +07:00
function init() {
2020-03-21 01:44:46 +07:00
proxy.translate.connect(translate);
2020-02-21 00:45:53 +07:00
setInterval(checkFinished, 300);
}