/* globals Vue */
// ==UserScript==
// @name 智能划词翻译
// @namespace translate.xinggsf
// @version 1.7.0
// @description 划词翻译。谷歌翻译和有道词典双引擎;CTRL + ?翻译剪贴板
// @author xinggsf 田雨菲
// @include http*
// @include file://*
// @exclude https://nnyy.in/*
// @exclude https://www.dandanzan.net/*
// @exclude https://www.dandanzan.com/*
// @run-at document-body
// @grant GM_addStyle
// @grant GM_xmlhttpRequest
// @require https://cdn.staticfile.org/vue/2.6.11/vue.min.js
// @connect fanyi.youdao.com
// @connect translate.googleapis.com
// @downloadURL https://update.greasyfork.icu/scripts/41076/%E6%99%BA%E8%83%BD%E5%88%92%E8%AF%8D%E7%BF%BB%E8%AF%91.user.js
// @updateURL https://update.greasyfork.icu/scripts/41076/%E6%99%BA%E8%83%BD%E5%88%92%E8%AF%8D%E7%BF%BB%E8%AF%91.meta.js
// ==/UserScript==
'use strict';
const youdaoUrl = 'http://fanyi.youdao.com/translate?&doctype=json&type=AUTO&i=';
const googleUrl = 'https://translate.googleapis.com/translate_a/single?client=gtx&dt=t&dt=bd&dj=1&source=input&hl=zh-CN&sl=auto&tl=';
const reHZ = /^[\u4E00-\u9FA5\uFF00-\uFF20\u3000-\u301C]/;
const countOfWord = s => s ? s.split(/\s+/).length : 0;
const isChina = s => reHZ.test(s);
const sleep = ms => new Promise(resolve => { setTimeout(resolve, ms) });
const xfetch = (url, type = 'json') => new Promise((success, fail) => {
GM_xmlhttpRequest({
method: 'GET',
timeout: 3000,
url: url,
responseType: type,
onload: success,
onerror: fail,
ontimeout: fail
});
});
const comTranslate = {
template: `
`,
data() {
return {
selText: '',
resultDOM: '',
position: { left: 0, top: 0 }
}
},
methods: {
showResult(text) { //显示翻译文本
if (!this.resultDOM) this.resultDOM = text;
else this.resultDOM += '
' + text;
},
query() {
const enc = encodeURIComponent(this.selText);
const url = googleUrl + (isChina(this.selText) ? 'en&q=' : 'zh-CN&q=') + enc;
this.selText = ''; // hide icon
xfetch(url).then(r => {
const ra = r.response.sentences; // 翻译结果数组
if (ra) this.showResult('谷歌翻译:
'+ ra.map(s => s.trans).join(''));
})
.catch (e => {
this.showResult('谷歌服务器连接失败');
});
xfetch(youdaoUrl + enc, 'text').then(r => {
const ro = JSON.parse(r.responseText.trim());
if (!ro || ro.errorCode != 0) return;
const html = ro.translateResult.reduce((a, b, i, arr) => {
const content = b.map(s => s.tgt).join('
');
return `${a}${content}
`;
}, '有道翻译:
');
this.showResult(html);
})
.catch (e => {
this.showResult('有道服务器连接失败');
});
},
async doClick(ev) {
if (ev.ctrlKey) {
this.selText = await readClipboard();
this.selText = this.selText.trim().replace(/\s{2,}/g, ' ');
if (!this.selText) return;
}
this.position.top = Math.min(this.position.top, window.innerHeight - 168);
this.position.left = Math.min(this.position.left, window.innerWidth - 450);
this.query();
}
},
computed: {
setPositionStyle() {
return `left:${this.position.left}px;top:${this.position.top}px;`;
}
},
mounted() {
document.addEventListener('mouseup', async ev => {
this.resultDOM = '';
this.position.left = ev.clientX;
this.position.top = ev.clientY + 12;
this.selText = String(window.getSelection()).trim().replace(/\s{2,}/g, ' ');
if (this.selText) {
await sleep(2000);
this.selText = '';
}
});
document.addEventListener('keydown', async ev => {
if (ev.ctrlKey && ev.keyCode == 191) {
let text = await readClipboard();
text = text.trim().replace(/\s{2,}/g, ' ');
if (text) {
this.selText = text;
this.query();
}
else if (this.selText) this.query();
}
});
}
};
GM_addStyle(`.gm-gg-yd-translate > .tip {
position:fixed;
z-index:21474836466 !important;
font-size:13px!important;
overflow:auto!important;
background:#fff!important;
font-family:sans-serif,Arial!important;
font-weight:normal!important;
text-align:left!important;
color:#000!important;
padding:0.5em 1em!important;
line-height:1.5em!important;
border-radius:5px!important;
border:1px solid #ccc!important;
box-shadow:4px 4px 8px #888!important;
max-width:450px!important;
max-height:333px!important;
}
.gm-gg-yd-translate > .icon {
position:fixed;
z-index:21474836466 !important;
width:32px!important;
height:32px!important;
background:#fff!important;
border-radius:50%!important;
box-shadow:4px 4px 8px #888!important;
}`);
const vm = new Vue({
render: h => h(comTranslate)
}).$mount();
document.documentElement.appendChild(vm.$el);
async function readClipboard() {
if (!window.isSecureContext) {
alert('不安全页面不允许读取剪贴板!');
return
}
await navigator.permissions.query({name: 'clipboard-read'});
try {
return await navigator.clipboard.readText();
} catch (ex) {
alert('请允许读取剪贴板!')
}
}