// ==UserScript==
// @name 智能划词翻译,可替换原文版
// @namespace https://greasyfork.org/zh-CN/scripts/382768
// @version 2.0.2
// @description 划词翻译,翻译后直接替换原来的文字,看英文技术文档专用
// @grant unsafeWindow
// @require http://cdn.bootcss.com/jquery/3.3.1/jquery.min.js
// @require https://cdn.bootcss.com/rangy/1.3.0/rangy-core.min.js
// @author 辣条要甜点
// @match http://*/*
// @include https://*/*
// @run-at document-end
// @connect dict.youdao.com
// @connect translate.google.cn
// @grant GM_xmlhttpRequest
// @downloadURL none
// ==/UserScript==
(function () {
'use strict';
rangy.init();
var youdaoUrl = 'http://dict.youdao.com/jsonapi?xmlVersion=5.1&jsonversion=2&q=';
var googleUrl = 'https://translate.google.cn/translate_a/single?client=gtx&dt=t&dt=bd&dj=1&source=input&hl=zh-CN&sl=auto&tl=';
var iconSize = 24;
var translationTestSize = 16;
var icon = document.createElement('div');
var style = '' +
'width:24px!important;' +
'height:24px!important;' +
'margin:4px!important;' +
'position:absolute!important;';
var iconStyle = '' +
'width:32px!important;' +
'height:32px!important;' +
'display:none!important;' +
'background:#fff!important;' +
'border-radius:16px!important;' +
'box-shadow:4px 4px 8px #888!important;' +
'position:absolute!important;' +
'z-index:2147483647!important;' +
'';
icon.innerHTML = '' +
'' +
'';
icon.setAttribute('style', iconStyle);
var selectText,fyDom,range,isL,isR,_t;
// 添加翻译图标到 DOM
document.documentElement.appendChild(icon);
// 鼠标事件:防止选中的文本消失
document.addEventListener('mousedown', function (e) {
if (e.target == icon || (e.target.parentNode && e.target.parentNode == icon) || (e.target.parentNode.parentNode && e.target.parentNode.parentNode == icon)) {// 点击了翻译图标
e.preventDefault();
}
});
// 选中变化事件:当点击已经选中的文本的时候,隐藏翻译图标和翻译面板(此时浏览器动作是:选中的文本已经取消选中了)
document.addEventListener("selectionchange", function () {
if (getFirstRange() && !rangy.getSelection().toString().trim()) {
icon.style.display = 'none';
server.containerDestroy();
}
});
// 鼠标事件:防止选中的文本消失;显示、隐藏翻译图标
document.addEventListener('mouseup', function (e) {
if (e.target == icon || (e.target.parentNode && e.target.parentNode == icon) || (e.target.parentNode.parentNode && e.target.parentNode.parentNode == icon)) {// 点击了翻译图标
e.preventDefault();
return;
}
for (var i = 0; i < server.rendered.length; i++) {// 点击了翻译内容面板
if (e.target == server.rendered[i])
return;// 不再创建翻译图标
}
range = getFirstRange();
selectText = range ? rangy.getSelection().toString() : '';
if (selectText && icon.style.display == 'none') {
icon.style.top = e.pageY + 12 + 'px';
icon.style.left = e.pageX + 'px';
icon.style.display = 'block';
} else {
icon.style.display = 'none';
server.containerDestroy();// 销毁翻译内容面板
}
});
// 翻译图标点击事件
icon.addEventListener('click', function (e) {
if (range) {
var html = rangy.getSelection().toHtml();
fyDom = document.createElement("div");
fyDom.innerHTML = html;
//自定义翻译的文本格式,谷歌翻译不会把|翻译,所以找到所有文本节点的text,组成"选择的dom下标-选择的dom下标>>text||||"
_t = '';
getDomText(fyDom, '');
isL = (html.substr(0, 1) == "<");
isR = (html.substr(-1) == ">");
icon.style.display = 'none';
server.containerDestroy();// 销毁翻译内容面板
// 新建翻译内容面板
var container = server.container();
container.style.top = e.pageY + 'px';
if (e.pageX + 350 <= document.body.clientWidth)// container 面板css最大宽度为250px
container.style.left = e.pageX + 'px';
else
container.style.left = document.body.clientWidth - 350 + 'px';
document.body.appendChild(container);
server.rendered.push(container);
if(isChina(selectText)) {
ajax(googleUrl + 'en&q=', encodeURIComponent(_t), 1, container);
} else {
if(countOfWord(selectText) == 1) {
ajax(youdaoUrl, selectText, 0, container);
}else {
ajax(googleUrl + 'zh-CN&q=', encodeURIComponent(_t), 1, container);
}
}
}
});
function countOfWord(str) {
var value = String(str);
value = value.replace(/^\s+|\s+$/gi, ""); // 前后空格不计算为单词数
value = value.replace(/\s+/gi, " ");// 多个空格替换成一个空格
var length = 0; // 更新计数
var match = value.match(/\s/g);//没有匹配到则返回null
if (match) {
length = match.length + 1;
} else if (value) {
length = 1;
}
return length;
}
function isChina(str){
var reg=/^([\u4E00-\u9FA5]|[\uFF00-\uFF20]|[\u3000-\u301C])+$/;
return !!reg.test(str);
}
// ajax 跨域访问公共方法
function ajax(url, text, target, element, method, data, headers) {
if (!!!method)
method = 'GET';
// >>>因为Tampermonkey跨域访问(a.com)时会自动携带对应域名(a.com)的对应cookie
// 不会携带当前域名的cookie
// 所以,GM_xmlhttpRequest【不存在】cookie跨域访问安全性问题
// 以下设置默认headers不起作用<<<
url += text;
if (!!!headers)
headers = { 'cookie': '' };
GM_xmlhttpRequest({
method: method,
url: url,
headers: headers,
data: data,
onload: function (res) {
if(target == 0){
youdao(res.responseText, text, element);
}else{
google(res.responseText, element);
}
},
onerror: function (res) {
displaycontainer("连接失败",element);
}
});
}
// 有道翻译 引擎
function youdao(rst, text, element) {
var ec = JSON.parse(rst).ec;
if (!!ec) {
var word = JSON.parse(rst).ec.word[0], html = '', tr = '';
var trs = word.trs, ukphone = word.ukphone, usphone = word.usphone, phone = word.phone;
var phoneStyle = '' +
'color:#9E9E9E!important;' +
'';
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 + ']
';
}
trs.forEach(element => {
tr += element.tr[0].l.i[0] + '
';
});
html += tr;
displaycontainer(html, element);
}else {
ajax(googleUrl +'zh-CN&q=', text, 1, element);
}
}
// 谷歌翻译 引擎
function google(rst, element) {
var json = JSON.parse(rst), html = '';
for (var i = 0; i < json.sentences.length; i++) {
html += json.sentences[i].trans.trim();
}
//解析格式
var arr = html.split("||||");
arr.pop();
for (var i in arr){
var _arr = arr[i].split('>>');
var j = 'fyDom';
var c = '';
for (var x in _arr) {
//第一个是dom数组的下标
if (x == 0) {
var __arr = _arr[x].split('-');
for (var _x in __arr){
j += '.childNodes["'+parseInt(__arr[_x])+'"]';
}
} else if (x == 1) {
c += TextEnCode(_arr[x]);
} else {
c += '>>'+TextEnCode(_arr[x]);
}
}
j += '.nodeValue="'+c+'"';
//为了方便直接组成js代码,执行
eval(j);
}
html = '