StrokesPlus.net
Welcome Guest! To enable all features please Login or Register.

Notification

Icon
Error

Options
Go to last post Go to first unread
soooulp  
#1 Posted : Saturday, February 12, 2022 5:13:31 AM(UTC)
soooulp

Rank: Advanced Member

Reputation:

Groups: Moderators, Approved
Joined: 4/23/2020(UTC)
Posts: 161
China

Thanks: 46 times
Was thanked: 23 time(s) in 17 post(s)
It will translate the selected text from any language to English, copy the result to the clipboard then show it near the mouse, and the result will auto disappear in 3s.

This script is from a translation script by Javascript on Tampermokey.

I set default translation from Auto to En in currLan and toLan variable. You can change it by your customized.
The Google Translations Language Support https://cloud.google.com/translate/docs/languages

Update:
20220306 Fix selected text with a newline

UserPostedImage

You also can set a click in Global Actions-Mouse Events-Left Click Script or mouse scroll in Global Actions-Mouse Events-Mouse Wheel Script to close the result Showbox.

Code:
if(!click.Down) {
    sp.DeleteSavedString('strTrans');
}


Edited by user Sunday, March 6, 2022 6:04:23 AM(UTC)  | Reason: Not specified

thanks 2 users thanked soooulp for this useful post.
Ola Boga on 3/2/2022(UTC), Syrianux on 2/15/2024(UTC)
Charles  
#2 Posted : Saturday, October 8, 2022 1:33:29 PM(UTC)
Charles

Rank: Newbie

Reputation:

Groups: Approved
Joined: 10/4/2019(UTC)
Posts: 3
China
Location: Shandong

Thanks: 2 times
大佬可否修改为有道版本?(Could you change it to a Youdao dict version?)

Here is the Tampermonkey Code:

Edited by user Sunday, October 9, 2022 8:40:04 AM(UTC)  | Reason: Not specified

Charles  
#3 Posted : Sunday, October 9, 2022 11:58:08 AM(UTC)
Charles

Rank: Newbie

Reputation:

Groups: Approved
Joined: 10/4/2019(UTC)
Posts: 3
China
Location: Shandong

Thanks: 2 times
I can make the cross-domain function work. Could you change it to the Youdao Dict version?
With reference to the Tampermonky

// ==UserScript==
// @id youdaodict-greasemonkey-reverland-2015-09-26
// @name youdaodict
// @name:zh-CN 有道取词
// @version 2.0
// @namespace https://github.com/HalfdogStudio/youdaodict
// @author Liu Yuyang(sa@linuxer.me)
// @description Translate any text selected into a tooltip
// @description:zh-cn 一个可以在浏览器中自由使用的屏幕取词脚本
// @include *
// @require https://greasemonkey.git...polyfill/gm4-polyfill.js
// @grant GM_xmlhttpRequest
// @grant GM.xmlHttpRequest
// ==/UserScript==

window.document.body.addEventListener("mouseup", translate, false);
window.document.body.addEventListener("keyup", toggleYoudao, false);
var toggle = true;

function toggleYoudao(e) {
if (e.which == 81 && e.altKey && e.ctrlKey) {
if (toggle) {
window.document.body.removeEventListener("mouseup", translate, false);
toggle = false;
} else {
window.document.body.addEventListener("mouseup", translate, false);
toggle = true;
}
}
}

function translate(e) {
// remove previous .youdaoPopup if exists
var previous = document.querySelector(".youdaoPopup");
if (previous) {
document.body.removeChild(previous);
}
//console.log("translate start");
var selectObj = document.getSelection();

// if #text node
if (selectObj.anchorNode && selectObj.anchorNode.nodeType == 3) {
//GM_log(selectObj.anchorNode.nodeType.toString());
var word = selectObj.toString();
if (word == "") {
return;
}
// linebreak wordwrap, optimize for pdf.js
word = word.replace('-\n','');
// multiline selection, optimize for pdf.js
word = word.replace('\n', ' ');
//console.log("word:", word);
var ts = new Date().getTime();
//console.log("time: ", ts);
var mx = e.clientX;
var my = e.clientY;
translate(word, ts);

}

function popup(mx, my, result) {
//console.log(mx)
//console.log(my)
//console.log("popup window!")
var youdaoWindow = document.createElement('div');
youdaoWindow.classList.toggle("youdaoPopup");
// parse
var dictJSON = JSON.parse(result);
console.log(dictJSON);
var query = dictJSON['query'];
var errorCode = dictJSON['errorCode'];
if (dictJSON['basic']) {
word();
} else {
sentence();
}
// main window
// first insert into dom then there is offsetHeight!IMPORTANT!
document.body.appendChild(youdaoWindow);
youdaoWindow.style.color = "teal";
youdaoWindow.style.textAlign = "left";
youdaoWindow.style.display = "block";
youdaoWindow.style.position = "fixed";
youdaoWindow.style.background = "whitesmoke";
youdaoWindow.style.borderRadius = "5px";
youdaoWindow.style.boxShadow = "0 0 5px 0";
youdaoWindow.style.opacity = "1";
youdaoWindow.style.width = "200px";
youdaoWindow.style.wordWrap = "break-word";
youdaoWindow.style.left = mx + 10 + "px";
if (mx + 200 + 30 >= window.innerWidth) {
youdaoWindow.style.left = parseInt(youdaoWindow.style.left) - 200 + "px";
}
if (my + youdaoWindow.offsetHeight + 30 >= window.innerHeight) {
youdaoWindow.style.bottom = "20px";
} else {
youdaoWindow.style.top = my + 10 + "px";
}
youdaoWindow.style.padding = "5px";
youdaoWindow.style.zIndex = '999999';

function word() {

function play(word) {
//console.log("[DEBUG] PLAYOUND")

function playSound(buffer) {
var source = context.createBufferSource();
source.buffer = buffer;
source.connect(context.destination);
source.start(0);
}

var context = new AudioContext();
var soundUrl = `https://dict.youdao.com/dictvoice?type=2&audio=${word}`;
var p = new Promise(function(resolve, reject) {
var ret = GM.xmlHttpRequest({
method: "GET",
url: soundUrl,
responseType: 'arraybuffer',
onload: function(res) {
try {
context.decodeAudioData(res.response, function(buffer) {
resolve(buffer);
});
} catch(e) {
reject(e);
}
}
});
});
p.then(playSound, function(e) {
console.log(e);
});
}

var basic = dictJSON['basic'];
var header = document.createElement('p');
// header
var span = document.createElement('span');
span.innerHTML = query;
header.appendChild(span);
// phonetic if there is
var phonetic = basic['phonetic'];
if (phonetic) {
var phoneticNode = document.createElement('span');
phoneticNode.innerHTML = '[' + phonetic + ']';
phoneticNode.style.cursor = "pointer";
header.appendChild(phoneticNode);
var playLogo = document.createElement('span');
header.appendChild(phoneticNode);
phoneticNode.addEventListener('mouseup', function(e){
if (e.target === phoneticNode) {
e.stopPropagation();
play(query);
}
}, false);
}
header.style.color = "darkBlue";
header.style.margin = "0";
header.style.padding = "0";
span.style.fontweight = "900";
span.style.color = "black";

youdaoWindow.appendChild(header);
var hr = document.createElement('hr');
hr.style.margin = "0";
hr.style.padding = "0";
hr.style.height = "1px";
hr.style.borderTop = "dashed 1px teal";
youdaoWindow.appendChild(hr);
var ul = document.createElement('ul');
// ul style
ul.style.margin = "0";
ul.style.padding = "0";
basic['explains'].map(function(trans) {
var li = document.createElement('li');
li.style.listStyle = "none";
li.style.margin = "0";
li.style.padding = "0";
li.style.background = "none";
li.style.color = "inherit";
li.appendChild(document.createTextNode(trans));
ul.appendChild(li);
});
youdaoWindow.appendChild(ul);

}

function sentence() {
var ul = document.createElement('ul');
// ul style
ul.style.margin = "0";
ul.style.padding = "0";
dictJSON['translation'].map(function(trans) {
var li = document.createElement('li');
li.style.listStyle = "none";
li.style.margin = "0";
li.style.padding = "0";
li.style.background = "none";
li.style.color = "inherit";
li.appendChild(document.createTextNode(trans));
ul.appendChild(li);
});
youdaoWindow.appendChild(ul);
}
}


function translate(word, ts) {
var reqUrl = `http://fanyi.youdao.com/openapi.do?type=data&doctype=json&version=1.1&relatedUrl=http%3A%2F%2Ffanyi.youdao.com%2F%23&keyfrom=fanyiweb&key=null&translate=on&q=${word}&ts=${ts}`;
//console.log("request url: ", reqUrl);
var ret = GM.xmlHttpRequest({
method: "GET",
url: reqUrl,
headers: {"Accept": "application/json"}, // can be omitted...
onreadystatechange: function(res) {
//console.log("Request state changed to: " + res.readyState);
},
onload: function(res) {
var retContent = res.response;
//console.log(retContent)
popup(mx, my, retContent);
},
onerror: function(res) {
console.log("error");
}
});
}
}
soooulp  
#4 Posted : Sunday, October 9, 2022 1:27:57 PM(UTC)
soooulp

Rank: Advanced Member

Reputation:

Groups: Moderators, Approved
Joined: 4/23/2020(UTC)
Posts: 161
China

Thanks: 46 times
Was thanked: 23 time(s) in 17 post(s)
Originally Posted by: Charles Go to Quoted Post
I can make the cross-domain function work. Could you change it to the Youdao Dict version?
With reference to the Tampermonky




Code:
sp.Sleep(400);
sp.SendModifiedVKeys([vk.LCONTROL], [vk.VK_C]);
sp.Sleep(100);
var text = clip.GetText();
text = text.replace('\r\n', '');
var currpt = sp.GetCurrentMousePoint();
var r={
    "wd":0,//中英文字数
    "nwd":0,//英数词数
    "nb":0,//数字词数
    "c":0,//字符数
    "cb":0,//非空格字符
    "r":0,//回车
    "en":0,//英文字母数
    "cn":0,//中文字数
    "bl":0//非回车空格
};
var words = text.match(/\w+([’\']\w+)?/g)||[];//含撇号(如I'm)的单词视为一个词
var cnwords = text.match(/[\u4e00-\u9fa5]/g)||[];//统一中文字范围
r.nwd = words.length;
r.cn = cnwords.length;


var httpHandler = new HttpClientHandler();
httpHandler.AutomaticDecompression = host.flags(DecompressionMethods.GZip, DecompressionMethods.Deflate);
var client = new HttpClient(httpHandler);

var response;
var result;
var strTrans = '';
var json;

if(r.nwd == 1) {
    client.BaseAddress = new Uri("https://dict.youdao.com/");
    response = client.GetAsync("jsonapi?xmlVersion=5.1&jsonversion=2&q=" + text).Result;
    result = response.Content.ReadAsStringAsync().Result;
    json = JSON.parse(result);
    var arr;
    if(json.ec) {
        arr = json.ec.word[0].trs;
    } else {
        arr = '';
        strTrans = '未识别单词';
    }
    for(i = 0; i < arr.length; i++) {
        if(i < arr.length -1) {
            if(arr[i].tr[0].l.i[0].length < 25) {
                strTrans = strTrans + arr[i].tr[0].l.i[0].slice(0, 25) + '\r\n';
            } else if(arr[i].tr[0].l.i[0].length > 25 && arr[i].tr[0].l.i[0].length < 50) {
                strTrans = strTrans + arr[i].tr[0].l.i[0].slice(0, 25) + '\r\n' +
                                        arr[i].tr[0].l.i[0].slice(25, 50) + '\r\n';
            } else if(arr[i].tr[0].l.i[0].length > 50 && arr[i].tr[0].l.i[0].length < 75) {
                strTrans = strTrans + arr[i].tr[0].l.i[0].slice(0, 25) + '\r\n' +
                                        arr[i].tr[0].l.i[0].slice(25, 50) + '\r\n' +
                                        arr[i].tr[0].l.i[0].slice(50, 75) + '\r\n';
            } else if(arr[i].tr[0].l.i[0].length > 75) {
                strTrans = strTrans + arr[i].tr[0].l.i[0].slice(0, 25) + '\r\n' +
                                        arr[i].tr[0].l.i[0].slice(25, 50) + '\r\n' +
                                        arr[i].tr[0].l.i[0].slice(50, 75) + '\r\n' +
                                        arr[i].tr[0].l.i[0].slice(75, 100) + '\r\n';
            }
        } else {
            if(arr[i].tr[0].l.i[0].length < 25) {
                strTrans = strTrans + arr[i].tr[0].l.i[0].slice(0, 25);
            } else if(arr[i].tr[0].l.i[0].length > 25 && arr[i].tr[0].l.i[0].length < 50) {
                strTrans = strTrans + arr[i].tr[0].l.i[0].slice(0, 25) + '\r\n' +
                                        arr[i].tr[0].l.i[0].slice(25, 50);
            } else if(arr[i].tr[0].l.i[0].length > 50 && arr[i].tr[0].l.i[0].length < 75) {
                strTrans = strTrans + arr[i].tr[0].l.i[0].slice(0, 25) + '\r\n' +
                                        arr[i].tr[0].l.i[0].slice(25, 50) + '\r\n' +
                                        arr[i].tr[0].l.i[0].slice(50, 75);
            } else if(arr[i].tr[0].l.i[0].length > 75) {
                strTrans = strTrans + arr[i].tr[0].l.i[0].slice(0, 25) + '\r\n' +
                                        arr[i].tr[0].l.i[0].slice(25, 50) + '\r\n' +
                                        arr[i].tr[0].l.i[0].slice(50, 75) + '\r\n' +
                                        arr[i].tr[0].l.i[0].slice(75, 100);
            }
        }
    }

} else {
    client.BaseAddress = new Uri("https://fanyi.youdao.com/");
    response = client.GetAsync("translate?&doctype=json&type=AUTO&i=" + text).Result;
    result = response.Content.ReadAsStringAsync().Result;
    json = JSON.parse(result);
    //StrokesPlus.Console.Log(json.translateResult[0][0].tgt);

    var arr;
    if(json.translateResult) {
        arr = json.translateResult[0][0].tgt;
        strTrans = arr;
        clip.SetText(arr);
    } else {
        arr = '';
        strTrans = '未识别划词';
    }

}

//sp.StoreBool("Trans", true);
//sp.CreateTimer('Trans', 6000, -1, String.raw`sp.StoreBool("Trans", false);sp.DeleteTimer('Trans');`);      

if(strTrans != null) {
    //clip.SetText(strTrans);
    sp.SaveString('strTrans', strTrans);
}

if(strTrans != null) {
    var info = new DisplayTextInfo();
    info.Opacity = 0.8;
    info.Padding = 5;   
    info.MessageAlignment = 'Left';
    info.MessageFont = new Font("Segoe UI Semibold", 8);
    info.Location = (currpt.X + 10) + ',' + (currpt.Y + 35);
    info.BackColor = "245,245,245"; 
    info.ForeColor = 'black';
    info.Duration = 3000;
    info.Message = sp.GetSavedString('strTrans').trim();
    info.UsePrimaryScreen = true; 
    sp.DisplayText(info);
}
httpHandler.Dispose();
client.Dispose();
response.Dispose();

Edited by user Sunday, October 9, 2022 1:58:02 PM(UTC)  | Reason: Not specified

Users browsing this topic
Forum Jump  
You cannot post new topics in this forum.
You cannot reply to topics in this forum.
You cannot delete your posts in this forum.
You cannot edit your posts in this forum.
You cannot create polls in this forum.
You cannot vote in polls in this forum.