// ==UserScript==
// @name 智能划词翻译 by xinggsf
// @namespace https://greasyfork.org/zh-CN/users/869804
// @version 0.0.2
// @description 划词翻译,使用有道词典api
// @author zhaowenlu xinggsf
// @include http*
// @run-at document-start
// @connect dict.youdao.com
// @grant GM_xmlhttpRequest
// @downloadURL https://update.greasyfork.icu/scripts/439188/%E6%99%BA%E8%83%BD%E5%88%92%E8%AF%8D%E7%BF%BB%E8%AF%91%20by%20xinggsf.user.js
// @updateURL https://update.greasyfork.icu/scripts/439188/%E6%99%BA%E8%83%BD%E5%88%92%E8%AF%8D%E7%BF%BB%E8%AF%91%20by%20xinggsf.meta.js
// ==/UserScript==
'use strict';
// const youdaoUrl = 'http://dict.youdao.com/jsonapi?xmlVersion=5.1&dicts={"count":99,"dicts":[["ec"]]}&jsonversion=2&q=';
const youdaoUrl = 'http://dict.youdao.com/jsonapi?jsonversion=2&xmlVersion=5.1&q='
const googleUrl = 'https://translate.google.cn/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);
// 翻译结果面板
class TranslateTip {
constructor() {
const div = document.createElement('div');
div.hidden = true;
div.setAttribute('style',
`position:absolute!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:350px!important;
max-height:216px!important;
z-index:2147483647!important;`
);
document.documentElement.appendChild(div);
//点击了翻译内容面板,不再创建翻译图标
div.addEventListener('mouseup', e => e.stopPropagation());
this._tip = div;
}
showText(text) { //显示翻译文本
this._tip.innerHTML = text;
this._tip.hidden = !1;
}
hide() {
this._tip.innerHTML = '';
this._tip.hidden = true;
}
pop(ev) {
this._tip.style.top = ev.pageY + 'px';
//面板最大宽度为350px
this._tip.style.left = (ev.pageX + 350 <= document.body.clientWidth ?
ev.pageX : document.body.clientWidth - 350) + 'px';
}
}
const tip = new TranslateTip();
class Icon {
constructor() {
const icon = document.createElement('span');
icon.hidden = true;
icon.innerHTML = ``;
icon.setAttribute('style',
`width:32px!important;
height:32px!important;
background:#fff!important;
border-radius:50%!important;
box-shadow:4px 4px 8px #888!important;
position:absolute!important;
z-index:2147483647!important;`
);
document.documentElement.appendChild(icon);
//拦截二个鼠标事件,以防止选中的文本消失
icon.addEventListener('mousedown', e => e.preventDefault(), true);
icon.addEventListener('mouseup', ev => ev.preventDefault(), true);
icon.addEventListener('click', ev => {
if (ev.ctrlKey) navigator.clipboard.readText()
.then(text => {
this.queryText(text.trim(),ev);
})
.catch(err => {
console.error('Failed to read clipboard contents: ', err);
});
else {
const text = window.getSelection().toString().trim().replace(/\s{2,}/g, ' ');
this.queryText(text,ev);
}
});
this._icon = icon;
}
pop(ev) {
const icon = this._icon;
icon.style.top = ev.pageY + 12 + 'px';
icon.style.left = ev.pageX + 'px';
icon.hidden = !1;
setTimeout(this.hide.bind(this), 2e3);
}
hide() {
this._icon.hidden = true;
}
queryText(text,ev) {
if (text) {
this._icon.hidden = true;
tip.pop(ev);
//const url = isChina(text) ? googleUrl +'en&q=' : countOfWord(text) == 1 ? youdaoUrl : googleUrl +'zh-CN&q=';
const url = youdaoUrl;
ajax(url, text);
}
}
}
const icon = new Icon();
document.addEventListener('mouseup', function(e) {
var text = window.getSelection().toString().trim();
if (!text) {
icon.hide();
tip.hide();
}
else icon.pop(e);
});
function ajax(url, text) {
const isYd = url.includes('//dict.youdao.');
url += encodeURIComponent(text);
console.log(url + "\n" + text);
GM_xmlhttpRequest({
method: 'GET',
responseType: 'json',
url: url,
onload: function(res) {
//isYd ? youdao(res.response, text) : google(res.response);
youdao(res.response, text);
},
onerror: function(res) {
console.log(res);
tip.showText("连接失败\nURL: "+ url);
}
});
}
function youdao(rst, text) {
if (!rst) {
//ajax(googleUrl + 'zh-CN&q=', text);
return;
}
let html = '';
if(!!rst.fanyi){
html += rst.fanyi.tran;
tip.showText(html);
return;
}
if(!!rst.ce){
let trsce = rst.ce.word[0].trs;
html += trsce.map(el => el.tr[0].l.i.map(w => w["#text"]).join(' ')).join('
');
tip.showText(html);
return;
}
if(!!rst.ec){
const { trs, ukphone, usphone, phone } = rst.ec.word[0];
if (!!ukphone && ukphone.length > 0) {
html = `英[${ukphone}]`;
}
if (!!usphone && usphone.length > 0) {
html += `美[${usphone}]`;
}
if (html.length > 0) {
html += '
';
} else if (!!phone && phone.length > 0) {
html += `[${phone}]`;
}
html += trs.map(el => el.tr[0].l.i[0]).join('
');
tip.showText(html);
return;
}
tip.showText(text);
}
function google(rst) {
console.log(rst)
let k, html = '';
for (k of rst.sentences) html += k.trans;
tip.showText(html);
}