// ==UserScript==
// @name 划词翻译
// @namespace http://www.icycat.com
// @description 选中文字按住左键一会儿后放开,自动翻译。
// @author 冻猫
// @include *
// @version 1.3
// @grant GM_xmlhttpRequest
// @grant GM_addStyle
// @run-at document-end
// ==/UserScript==
(function() {
'use strict';
function init() {
var timer, holdTime, isBox, word;
document.addEventListener('mousedown', mouseStart, false);
document.addEventListener('mouseup', mouseEnd, false);
function mouseStart(e) {
if (!document.getElementById('catTipBox')) {
createTipBox();
}
if (!/catTranslate/i.test(e.target.className)) {
document.getElementById('catTipBox').style.display = '';
document.getElementById('catContentBox').innerHTML = '翻译中...';
}
if (e.target.id == 'catPlaySound') {
document.getElementById('catPlaySound').classList.add('catPlaySoundClick');
getSound(word);
}
document.addEventListener('mousemove', moveCheck, false);
}
function moveCheck() {
clearTimeout(timer);
timer = setTimeout(function() {
holdTime = true;
}, 500);
}
function mouseEnd() {
document.removeEventListener('mousemove', moveCheck, false);
if (document.getElementById('catPlaySound')) {
document.getElementById('catPlaySound').classList.remove('catPlaySoundClick');
}
clearTimeout(timer);
if (holdTime && window.getSelection().toString()) {
holdTime = false;
console.log('开始翻译');
showTipBox();
word = window.getSelection().toString();
getTranslate(word, new Date().getTime());
}
}
}
function createTipBox() {
GM_addStyle([
'#catTipBox {font:normal 12px/24px Helvetica, Tahoma, Arial, sans-serif;text-align: left;position: absolute;z-index: 2147483647;top: 22px;left: -35px;background: #fff;border: 1px solid #dcdcdc;border: 1px solid rgba(0,0,0,.2);-webkit-transition: opacity .218s;transition: opacity .218s;-webkit-box-shadow: 0 2px 4px rgba(0,0,0,.2);box-shadow: 0 2px 4px rgba(0,0,0,.2);padding: 5px 0;display: none;font-size: 12px;line-height: 20px;}',
'#catContentBox {margin:0 8px;color:#333;}',
'#catContentBox .catWordBox{margin: 2px 0 1px 0;}',
'#catContentBox .catWord{font-size:14px;margin: 3px 0 3px;font-weight: bold;color:#333;}',
'#catContentBox span{margin-left: 5px;color:#333;font-weight: normal;font-size:12px;}',
'#catPlaySound {cursor:pointer;display: inline-block;vertical-align: middle;width: 14px;height: 11px;overflow: hidden;background: url("data:image/gif;base64,R0lGODlhDgAZAIAAABy3/f///yH5BAAAAAAALAAAAAAOABkAAAI1jA+nC7ncXmg0RlTvndnt7jlcxkmjqWzotLbui4qxqBpUmoDl2Nk5GOKRSsCfDyer7ZYMSQEAOw==") no-repeat;text-decoration: none;}',
'#catPlaySound.catPlaySoundClick {background-position:0 -14px;}',
'.catTipArrow {width: 0;height: 0;font-size: 0;line-height: 0;display: block;position: absolute;top: -16px;left: 10px;}',
'.catTipArrow em, .catTipArrow ins {width: 0;height: 0;font-size: 0;line-height: 0;display: block;position: absolute;border: 8px solid transparent;border-style: dashed dashed solid;}',
'.catTipArrow em {border-bottom-color: #d8d8d8;font-style: normal;color: #c00;}',
'.catTipArrow ins {border-bottom-color: #fff;top: 2px;text-decoration: underline;}'
].join('\n'));
var catTipBox = document.createElement('div');
catTipBox.id = 'catTipBox';
catTipBox.className = 'catTranslate';
var catContentBox = document.createElement('div');
catContentBox.id = 'catContentBox';
catContentBox.className = 'catTranslate';
var catTipArrow = document.createElement('div');
catTipArrow.className = 'catTipArrow';
catTipArrow.appendChild(document.createElement('em'));
catTipArrow.appendChild(document.createElement('ins'));
catTipBox.appendChild(catContentBox);
catTipBox.appendChild(catTipArrow);
document.body.appendChild(catTipBox);
}
function parseRes(jsonRes) {
var catContentBox = document.getElementById('catContentBox');
catContentBox.innerHTML = '';
var obj = JSON.parse(jsonRes);
if (obj.basic) {
var catWordBox = document.createElement('div');
catWordBox.className = 'catWordBox catTranslate';
if (obj.basic.phonetic) {
var catWord = document.createElement('span');
catWord.className = 'catWord catTranslate';
catWord.innerHTML = obj.query;
catWordBox.appendChild(catWord);
var catPhonetic = document.createElement('span');
catPhonetic.className = 'catTranslate';
catPhonetic.innerHTML = '[' + obj.basic.phonetic + ']';
catWordBox.appendChild(catPhonetic);
if (/^[a-zA-Z]+$/.test(obj.query)) {
var catPlaySound = document.createElement('span');
catPlaySound.id = 'catPlaySound';
catPlaySound.className = 'catTranslate';
catWordBox.appendChild(catPlaySound);
}
}
catContentBox.appendChild(catWordBox);
var explains = '';
for (var i = 0; i < obj.basic.explains.length; i++) {
if (i > 0) {
explains = explains + '<br />';
}
explains = explains + obj.basic.explains[i];
}
var catExplains = document.createElement('div');
catExplains.className = 'catTranslate';
catExplains.innerHTML = explains;
catContentBox.appendChild(catExplains);
} else {
explains = obj.translation[0];
catContentBox.innerHTML = explains;
}
}
function showTipBox() {
var catTipBox = document.getElementById('catTipBox');
var selectedRect = window.getSelection().getRangeAt(0).getBoundingClientRect();
var scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
if (/Firefox/i.test(navigator.userAgent)) {
catTipBox.style.top = scrollTop + selectedRect.y + selectedRect.height + 8 + 'px';
catTipBox.style.left = selectedRect.x + selectedRect.width / 2 - 18 + 'px';
} else {
catTipBox.style.top = scrollTop + selectedRect.top + selectedRect.height + 8 + 'px';
catTipBox.style.left = selectedRect.left + selectedRect.width / 2 - 18 + 'px';
}
catTipBox.style.display = 'block';
}
function playSound(arraybuffer) {
var audioCtx = new AudioContext();
audioCtx.decodeAudioData(arraybuffer).then(function(buffer) {
var source = audioCtx.createBufferSource();
source.buffer = buffer;
source.connect(audioCtx.destination);
source.start();
});
}
function getSound(word) {
GM_xmlhttpRequest({
method: "GET",
url: 'https://dict.youdao.com/dictvoice?type=2&audio=' + word,
responseType: 'arraybuffer',
onload: function(res) {
playSound(res.response);
},
});
}
function getTranslate(word, time) {
GM_xmlhttpRequest({
method: "GET",
url: 'http://fanyi.youdao.com/openapi.do?type=data&doctype=json&version=1.1&relatedUrl=http%3A%2F%2Ffanyi.youdao.com%2F&keyfrom=fanyiweb&key=null&translate=on&q=' + word + '&ts=' + time,
onload: function(res) {
parseRes(res.responseText);
},
});
}
init();
})();