ScreenTranslator/translators/papago.js

76 lines
2.1 KiB
JavaScript
Raw Normal View History

2020-03-21 01:44:46 +07:00
var lastText = '';
var active = window.location.href !== "about:blank";
2019-09-18 03:07:49 +07:00
2020-03-21 01:44:46 +07:00
function getText() {
let spans = [].slice.call(document.querySelectorAll('#txtTarget span'));
let text = spans.reduce(function (res, i) {
return res + i.innerText + ' ';
}, '');
2019-09-18 03:07:49 +07:00
2020-03-21 01:44:46 +07:00
return text.trim()
2019-09-18 03:07:49 +07:00
}
2020-03-21 01:44:46 +07:00
function checkFinished() {
if (!active) return;
let text = getText()
if (text === lastText || text === lastText + '...' || text === '')
2019-09-18 03:07:49 +07:00
return;
2020-03-21 01:44:46 +07:00
active = false;
// maybe translation will be updated
setTimeout(function() {
text = getText();
console.log('translated text', text, 'old', lastText, 'size', text.length, lastText.length);
lastText = text;
active = false;
proxy.setTranslated(text);
}, 1000);
2019-09-18 03:07:49 +07:00
}
2020-03-21 01:44:46 +07:00
function translate(text, from, to) {
console.log('start translate', text, from, to)
2021-01-05 21:03:11 +07:00
if (text.trim().length == 0) {
proxy.setTranslated('');
return;
}
2020-03-21 01:44:46 +07:00
let supported = ['ko', 'ru', 'en', 'fr', 'pt', 'th', 'ja',
'zh-CN', 'zh-TW', 'de', 'it', 'id', 'es', 'vi', 'hi'];
2019-09-18 03:07:49 +07:00
2020-03-21 01:44:46 +07:00
if (supported.indexOf(from) == -1) {
proxy.setFailed('Source language not supported');
2019-09-18 03:07:49 +07:00
return;
}
2020-03-21 01:44:46 +07:00
if (supported.indexOf(to) == -1) {
proxy.setFailed('Target language not supported');
return;
2019-09-18 03:07:49 +07:00
}
2020-03-21 01:44:46 +07:00
lastText = getText(); // because it can be updated after previous translation
active = true;
let langs = '?sk=auto&tk=' + to + '&';
if (window.location.href.indexOf('//papago.naver.com/') !== -1
&& window.location.href.indexOf(langs) !== -1) {
2021-01-05 21:03:11 +07:00
var input = document.querySelector('textarea#txtSource');
if (input.value == text) {
console.log('using cached result');
lastText = '';
return;
}
input.value = text;
input.dispatchEvent(new Event("input", { bubbles: true, cancelable: true }));
2020-03-21 01:44:46 +07:00
return;
2019-09-18 03:07:49 +07:00
}
2020-03-21 01:44:46 +07:00
2020-04-03 22:38:59 +07:00
let url = 'https://papago.naver.com/?sk=auto&tk=' + to + '&st=' + encodeURIComponent(text);
2020-04-12 21:01:59 +07:00
window.location = url;
2020-03-21 01:44:46 +07:00
}
function init() {
proxy.translate.connect(translate);
setInterval(checkFinished, 300);
2019-09-18 03:07:49 +07:00
}