diff --git a/CHANGELOG.md b/CHANGELOG.md index c143c8f..9ea7795 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,9 @@ +###ver 0.8.20 ++ 重新整理代码结构,重新组织类结构,方便扩展 ++ 新增扇贝单词、好学单词查询接口 ++ 新增自动加入扇贝单词生词本功能,方便学习 ++ 新增扇贝单词登陆检测,当启用自动加入生词本时,若没有登陆扇贝单词,则提示登陆并跳转 + ###ver 0.8.19 + 修改边栏显示的查词结果被某些网页导航条遮挡的 bug diff --git a/ChaZD.crx b/ChaZD.crx index f02cc13..951d4e8 100644 Binary files a/ChaZD.crx and b/ChaZD.crx differ diff --git a/README.md b/README.md index 96ff143..c61857f 100644 --- a/README.md +++ b/README.md @@ -2,12 +2,13 @@ ChaZD ===== ChaZD 查字典,简洁易用的英汉字典扩展程序,支持划词哦:) -翻译结果和发音朗读由**有道翻译**驱动。 +翻译结果和发音朗读由**有道翻译**驱动; +新增自动加入扇贝单词生词本功能,方便学习; +新增扇贝单词登陆检测,当启用自动加入生词本时,若没有登陆扇贝单词,则提示登陆并跳转。 获取 ----------- -+ [Chrome 网上应用商店](https://chrome.google.com/webstore/detail/chazd/nkiipedegbhbjmajlhpegcpcaacbfggp) -+ [crx 文件](https://github.com/ververcpp/ChaZD/blob/master/ChaZD.crx?raw=true) ++ [crx 文件](https://github.com/XYUU/ChaZD/blob/master/ChaZD.crx?raw=true) **注**:安装扩展后,第一次使用请刷新要查词的页面,划词功能才会生效; **注2**:非中文版Chrome浏览器的用户,如出现插件弹出窗口字体无法正常显示的情况,麻烦请更改浏览器的最小字号为12px diff --git a/manifest.json b/manifest.json index f6e4ea4..5ea88c6 100644 --- a/manifest.json +++ b/manifest.json @@ -1,32 +1,35 @@ { "manifest_version": 2, - - "name": "ChaZD", - "version": "0.8.19", - "description": "ChaZD 查字典,简洁易用的英汉字典扩展程序,支持划词哦:)", + "name": "好学单词", + "version": "0.8.20", + "description": "好学单词,简洁易用的英汉字典扩展程序,支持划词哦:)", "permissions": [ "https://dict.youdao.com/*", "https://fanyi.youdao.com/*", "http://dict.youdao.com/*", "http://fanyi.youdao.com/*", + "http://dict.xyuu.com.cn/*", + "http://*.shanbay.com/*", "contextMenus", "tabs", "storage", "notifications" ], - + //"content_security_policy": "script-src 'self' 'unsafe-eval'; object-src 'self';media-src '*'", "options_page": "options.html", "background": { "persistent": true, "scripts": [ "public/js/utility.min.js", "public/js/background.min.js" ] + //"scripts": [ "src/javascript/utility.js", "src/javascript/background.js" ] }, "content_scripts": [ { "all_frames": true, "css": ["public/css/inPage.min.css"], "js": ["public/js/utility.min.js", "public/js/selection.min.js"], + //"js": ["src/javascript/utility.js", "src/javascript/selection.js"], "matches": [""] } ], diff --git a/options.html b/options.html index d458a07..3a78dda 100644 --- a/options.html +++ b/options.html @@ -2,7 +2,7 @@ - ChaZD Options + 好学单词 设置 diff --git a/popup.html b/popup.html index a24962a..0b46a4b 100644 --- a/popup.html +++ b/popup.html @@ -29,10 +29,22 @@ (鼠标悬停查看说明) +
+ +
(说明)
+
+ +

@@ -54,12 +66,13 @@
- 默认发音 -- + 默认发音 +

- - + + \ No newline at end of file diff --git a/public/js/background.min.js b/public/js/background.min.js index 25e9a0e..6839962 100644 --- a/public/js/background.min.js +++ b/public/js/background.min.js @@ -1 +1 @@ -function ChaZD(a,b,c,d){this.wordSource=c,this.useHttps=b;var e=(b?urls.dictHttps:urls.dict)+a,f=this,g=new XMLHttpRequest;g.open("GET",e,!0),g.onreadystatechange=function(){if(4==g.readyState){var e=JSON.parse(g.responseText);if(-1===a.indexOf("-")||f.checkErrorCode(e.errorCode).error||f.haveTranslation(e)){var h=f.parseResult.call(f,e);d(h)}else new ChaZD(a.replace(/-/g," "),b,c,d)}},g.send()}function preprocessWord(a){return-1===a.indexOf(" ")&&(a=a.replace(/_/g," "),/[a-z]+/.test(a)&&(a=trim(a.replace(/([A-Z])/g," $1")))),a}function showNotification(a){if(Notifications){var b=null,c=Notifications.checkPermission();return 0===c?(b=Notifications.createNotification(a.icon||chrome.extension.getURL("icons/icon128.png"),a.title||"ChaZD 查字典",a.content),b.onclick=function(){window.open("https://chrome.google.com/webstore/detail/chazd/nkiipedegbhbjmajlhpegcpcaacbfggp")},b.show()):Notifications.requestPermission(),b}}ChaZD.prototype.checkErrorCode=function(a){var b={message:"",error:0,errorCode:0};switch(a){case 0:b.message="query success";break;case 20:b.message="要翻译的文本过长",b.error=1,b.errorCode=20;break;case 30:b.message="无法进行有效的翻译",b.error=1,b.errorCode=30;break;case 40:b.message="不支持的语言类型",b.error=1,b.errorCode=40;break;case 50:b.message="无效的key",b.error=1,b.errorCode=50;break;case 60:b.message="无辞典结果",b.error=1,b.errorCode=60}return b},ChaZD.prototype.parseResult=function(a){var b={},c=this.checkErrorCode(a.errorCode);if(b.haveWebTranslation=!1,c.error)b.errorCode=c.errorCode;else{var d=this.initTitle(a);if(b.titleBlock=d.titleBlock,b.haveTranslation=this.haveTranslation(a),void 0!==a.basic){var e=this.parseBasicResult(a);b.basicBlock=e}if(void 0!==a.web){var f=this.parseWebResult(a);b.haveWebTranslation=!0,b.webBlock=f}}return b.validMessage=c.message,b},ChaZD.prototype.haveTranslation=function(a){if(this.checkErrorCode(a.errorCode).error)return!1;var b=a.translation,c=a.query;return trim(c.toLowerCase())===trim(b.toString().toLowerCase())?!1:!0},ChaZD.prototype.initTitle=function(a){var b=a.translation,c=a.query,d=this.initVoice(c);c=c.length>=50&&"select"==this.wordSource?this.shortWord(c):c;var e=fmt(frame.titleWord,c,d),f=fmt(frame.titleTranslation,b.toString());return{titleBlock:fmt(frame.titleContainer,e,f,c.length>=50?"long-text":"")}},ChaZD.prototype.shortWord=function(a){return a.slice(0,a.lastIndexOf(" ",50)).concat(" ...")},ChaZD.prototype.parseBasicResult=function(a){var b=a.basic,c=a.query,d=this.parseBasicPhonetic(b,c),e=this.parseBasicExplains(b,c),f=fmt(frame.basicContainer,d,e);return f},ChaZD.prototype.parseBasicPhonetic=function(a,b){var c=a["uk-phonetic"],d=a["us-phonetic"];if(void 0!==c&&void 0!==d){var e=this.initVoice(b,1),f=fmt(frame.ukPhoneticContainer,"["+c+"]"+e),g=this.initVoice(b,2),h=fmt(frame.usPhoneticContainer,"["+d+"]"+g);return fmt(frame.phoneticContainer,f,h)}return fmt(frame.phoneticContainer,"","")},ChaZD.prototype.initVoice=function(a,b){var c=(this.useHttps?urls.voiceHttps:urls.voice)+a;void 0!==b&&(c=c+"&type="+b);var d="";return d=1===b?"英音":2===b?"美音":"真人发音",fmt(frame.voiceContainer,c,d)},ChaZD.prototype.parseBasicExplains=function(a){var b,c=a.explains,d="";for(b=0;b词典君正在翻译。。。"),a?($input.value=a,chrome.extension.sendMessage({queryWord:a,source:"popup",useHttps:useHttpsValue},buildResult)):chrome.extension.sendMessage({queryWord:$input.value,source:"popup",useHttps:useHttpsValue},buildResult)}function buildVoice(a){var b=a.getAttribute("data-src"),c=document.createElement("audio");c.setAttribute("src",b),a.appendChild(c),c.addEventListener("ended",function(){this.load()}),a.addEventListener("click",function(){c.play()})}function createLink(a,b){a.addEventListener("click",function(){chrome.tabs.create({url:b})})}function totalHeight(a){for(var b=document.getElementsByClassName(a),c=b.length,d=0,e=0;c>e;e++)d+=b[e].scrollHeight;return d+10}var $button=document.querySelector("#search"),$input=document.querySelector("#query-word"),$queryResultContainer=document.querySelector("#query-result");-1!==window.navigator.platform.toLowerCase().indexOf("mac")&&(document.querySelector("#ctrl-option").firstChild.nodeValue="Command");var buildResult=function(a){var b=a,c="";if("query success"==b.validMessage){c+=b.titleBlock,void 0!==b.basicBlock&&(c+=b.basicBlock),void 0!==b.webBlock&&(c+=b.webBlock),$queryResultContainer.innerHTML=c;var d,e,f=document.querySelectorAll(".voice-container");for(d=0,e=f.length;e>d;d++)buildVoice(f[d])}else $queryResultContainer.innerHTML=20==b.errorCode?"

这段文字太长,词典君无能为力了(┬_┬)

试试短一点的吧~

":40==b.errorCode?"

对不起,这段文字太高深了,请饶过词典君吧(┬_┬)

":"

词典君罢工啦(┬_┬)

是不是网络不太好?

稍后再试一次吧

"};$button.addEventListener("click",function(){queryInPopup()}),$input.select(),$input.addEventListener("input",function(){var a=$input.value;setTimeout(function(){$input.value===a&&""!==$input.value&&queryInPopup()},500)});var issue=document.querySelector("#issue"),email=document.querySelector("#email"),source=document.querySelector("#source"),keySet=document.querySelector("#key-set"),score=document.querySelector("#score");createLink(email,"mailto:ververcpp@gmail.com"),createLink(source,"https://github.com/ververcpp/ChaZD"),createLink(issue,"https://github.com/ververcpp/ChaZD/issues/new"),createLink(keySet,"chrome://extensions/configureCommands"),createLink(score,"https://chrome.google.com/webstore/detail/chazd/nkiipedegbhbjmajlhpegcpcaacbfggp"),document.querySelector("#setting-button").addEventListener("click",function(){var a=document.getElementById("settings");a.classList.toggle("active"),a.style.height=a.classList.contains("active")?blockHeight+"px":0});var blockHeight=totalHeight("top-menu")+totalHeight("sub-menu")+totalHeight("carved")+32,linkQuery=document.querySelector("#linkQuery"),noSelect=document.querySelector("#noSelect"),mouseSelect=document.querySelector("#mouseSelect"),useCtrl=document.querySelector("#useCtrl"),autoAudio=document.querySelector("#autoAudio"),defaultUk=document.querySelector("#defaultUk"),defaultUs=document.querySelector("#defaultUs"),showPositionSide=document.querySelector("#showPositionSide"),showPositionNear=document.querySelector("#showPositionNear"),autoHide=document.querySelector("#autoHide"),showDuration=document.querySelector("#showDuration"),currentDuration=document.querySelector("#currentDuration"),turnOffTips=document.querySelector("#turn-off-tips"),tips=document.querySelector("#tips"),toggleKey=document.querySelector("#toggle-key"),useHttps=document.querySelector("#useHttps"),useHttpsValue=!1;chrome.storage.sync.get(null,function(a){""!==a.currentWord&&queryInPopup(a.currentWord),a.linkQuery===!0?(linkQuery.checked=!0,linkQuery.nextSibling.classList.remove("unactive")):(linkQuery.checked=!1,linkQuery.nextSibling.classList.add("unactive")),a.useHttps===!0?(useHttps.checked=!0,useHttpsValue=!0,useHttps.nextSibling.classList.remove("unactive")):(useHttps.checked=!1,useHttpsValue=!1,useHttps.nextSibling.classList.add("unactive")),a.autoAudio===!0?(autoAudio.checked=!0,autoAudio.nextSibling.classList.remove("unactive")):(autoAudio.checked=!1,autoAudio.nextSibling.classList.add("unactive")),1===a.defaultVoice?(defaultUk.checked=!0,defaultUk.nextSibling.classList.remove("unactive"),defaultUs.nextSibling.classList.add("unactive")):2===a.defaultVoice&&(defaultUs.checked=!0,defaultUs.nextSibling.classList.remove("unactive"),defaultUk.nextSibling.classList.add("unactive")),"noSelect"===a.selectMode&&(noSelect.checked=!0,noSelect.nextSibling.classList.remove("unactive"),mouseSelect.nextSibling.classList.add("unactive"),useCtrl.nextSibling.classList.add("unactive"),toggleKey.disabled=!0,autoAudio.disabled=!0),"mouseSelect"===a.selectMode&&(mouseSelect.checked=!0,mouseSelect.nextSibling.classList.remove("unactive"),noSelect.nextSibling.classList.add("unactive"),useCtrl.nextSibling.classList.add("unactive"),toggleKey.disabled=!0,autoAudio.disabled=!1),"useCtrl"===a.selectMode&&(useCtrl.checked=!0,useCtrl.nextSibling.classList.remove("unactive"),noSelect.nextSibling.classList.add("unactive"),mouseSelect.nextSibling.classList.add("unactive"),toggleKey.disabled=!1,autoAudio.disabled=!1),a.showTips&&tips.classList.remove("unshow"),"side"===a.showPosition?(showPositionSide.checked=!0,showPositionSide.nextSibling.classList.remove("unactive"),showPositionNear.nextSibling.classList.add("unactive")):"near"===a.showPosition&&(showPositionNear.checked=!0,showPositionSide.nextSibling.classList.add("unactive"),showPositionNear.nextSibling.classList.remove("unactive")),"ctrl"===a.toggleKey?toggleKey.selectedIndex=0:"alt"===a.toggleKey?toggleKey.selectedIndex=1:"shift"===a.toggleKey&&(toggleKey.selectedIndex=2),a.autoHide===!0?(autoHide.checked=!0,autoHide.nextSibling.classList.remove("unactive"),showDuration.disabled=!1):(autoHide.checked=!1,autoHide.nextSibling.classList.add("unactive"),showDuration.disabled=!0),currentDuration.innerHTML=showDuration.value=a.showDuration}),linkQuery.addEventListener("click",function(){var a=linkQuery.checked;linkQuery.nextSibling.classList.toggle("unactive"),chrome.storage.sync.set({linkQuery:a},function(){})}),useHttps.addEventListener("click",function(){var a=useHttps.checked;useHttps.nextSibling.classList.toggle("unactive"),chrome.storage.sync.set({useHttps:a})}),autoAudio.addEventListener("click",function(){var a=autoAudio.checked;a?autoAudio.nextSibling.classList.remove("unactive"):autoAudio.nextSibling.classList.add("unactive"),chrome.storage.sync.set({autoAudio:a},function(){})}),defaultUk.addEventListener("click",function(){defaultUk.nextSibling.classList.remove("unactive"),defaultUs.nextSibling.classList.add("unactive"),chrome.storage.sync.set({defaultVoice:1},function(){})}),defaultUs.addEventListener("click",function(){defaultUs.nextSibling.classList.remove("unactive"),defaultUk.nextSibling.classList.add("unactive"),chrome.storage.sync.set({defaultVoice:2},function(){})}),turnOffTips.addEventListener("click",function(){tips.classList.add("unshow"),chrome.storage.sync.set({showTips:!1},function(){})}),noSelect.addEventListener("click",function(){toggleKey.disabled=!0,autoAudio.disabled=!0,noSelect.nextSibling.classList.remove("unactive"),mouseSelect.nextSibling.classList.add("unactive"),useCtrl.nextSibling.classList.add("unactive"),chrome.storage.sync.set({selectMode:"noSelect"},function(){})}),mouseSelect.addEventListener("click",function(){toggleKey.disabled=!0,autoAudio.disabled=!1,noSelect.nextSibling.classList.add("unactive"),mouseSelect.nextSibling.classList.remove("unactive"),useCtrl.nextSibling.classList.add("unactive"),chrome.storage.sync.set({selectMode:"mouseSelect"},function(){})}),useCtrl.addEventListener("click",function(){toggleKey.disabled&&(toggleKey.disabled=!1),autoAudio.disabled=!1,noSelect.nextSibling.classList.add("unactive"),mouseSelect.nextSibling.classList.add("unactive"),useCtrl.nextSibling.classList.remove("unactive"),chrome.storage.sync.set({selectMode:"useCtrl"},function(){})}),showPositionSide.addEventListener("click",function(){showPositionSide.nextSibling.classList.remove("unactive"),showPositionNear.nextSibling.classList.add("unactive"),chrome.storage.sync.set({showPosition:"side"},function(){})}),showPositionNear.addEventListener("click",function(){showPositionSide.nextSibling.classList.add("unactive"),showPositionNear.nextSibling.classList.remove("unactive"),chrome.storage.sync.set({showPosition:"near"},function(){})}),autoHide.addEventListener("click",function(){var a=autoHide.checked;a?(autoHide.nextSibling.classList.remove("unactive"),showDuration.disabled=!1):(autoHide.nextSibling.classList.add("unactive"),showDuration.disabled=!0),chrome.storage.sync.set({autoHide:a},function(){})}),showDuration.addEventListener("input",function(){currentDuration.innerHTML=showDuration.value,chrome.storage.sync.set({showDuration:showDuration.value},function(){})}),toggleKey.onchange=function(){chrome.storage.sync.set({toggleKey:this.value},function(){})}; \ No newline at end of file +function queryInPopup(a){$queryResultContainer.classList.contains("unshow")&&$queryResultContainer.classList.remove("unshow"),""!==$input.value&&($queryResultContainer.innerHTML="ψ(._. )>词典君正在翻译。。。"),a?($input.value=a,chrome.extension.sendMessage({queryWord:a,source:"popup"},buildResult)):chrome.extension.sendMessage({queryWord:$input.value,source:"popup"},buildResult)}function createLink(a,b){a.addEventListener("click",function(a){chrome.tabs.create({url:b})})}function totalHeight(a){for(var b=document.getElementsByClassName(a),c=b.length,d=0,e=0;c>e;e++)d+=b[e].scrollHeight;return d+10}var $button=document.querySelector("#search"),$input=document.querySelector("#query-word"),$queryResultContainer=document.querySelector("#query-result");-1!==window.navigator.platform.toLowerCase().indexOf("mac")&&(document.querySelector("#ctrl-option").firstChild.nodeValue="Command");var buildResult=function(a){var b=a,c="";if(0==b.Code){c+=b.titleBlock,void 0!==b.basicBlock&&(c+=b.basicBlock),void 0!==b.webBlock&&(c+=b.webBlock),$queryResultContainer.innerHTML=c;var d,e,f=document.querySelectorAll(".voice-container"),g=function(a){var b=a.getAttribute("data-src"),c=document.createElement("audio");c.setAttribute("src",b),a.appendChild(c),c.addEventListener("ended",function(a){this.load()}),a.addEventListener("click",function(a){c.play()})};for(d=0,e=f.length;e>d;d++)g(f[d])}else 20==b.Code?$queryResultContainer.innerHTML="

这段文字太长,词典君无能为力了(┬_┬)

试试短一点的吧~

":40==b.Code?$queryResultContainer.innerHTML="

对不起,这段文字太高深了,请饶过词典君吧(┬_┬)

":$queryResultContainer.innerHTML="

词典君罢工啦(┬_┬)

是不是网络不太好?

稍后再试一次吧

"};$button.addEventListener("click",function(a){queryInPopup()}),$input.select(),$input.addEventListener("input",function(a){var b=$input.value;setTimeout(function(){$input.value===b&&""!==$input.value&&queryInPopup()},500)});var issue=document.querySelector("#issue"),email=document.querySelector("#email"),source=document.querySelector("#source"),keySet=document.querySelector("#key-set"),score=document.querySelector("#score");createLink(email,"mailto:ververcpp@gmail.com"),createLink(source,"https://github.com/ververcpp/ChaZD"),createLink(issue,"https://github.com/ververcpp/ChaZD/issues/new"),createLink(keySet,"chrome://extensions/configureCommands"),createLink(score,"https://chrome.google.com/webstore/detail/chazd/nkiipedegbhbjmajlhpegcpcaacbfggp"),document.querySelector("#setting-button").addEventListener("click",function(a){var b=document.getElementById("settings");b.classList.toggle("active"),b.classList.contains("active")?b.style.height=blockHeight+"px":b.style.height=0});var blockHeight=totalHeight("top-menu")+totalHeight("sub-menu")+totalHeight("carved")+52,linkQuery=document.querySelector("#linkQuery"),noSelect=document.querySelector("#noSelect"),mouseSelect=document.querySelector("#mouseSelect"),useCtrl=document.querySelector("#useCtrl"),autoAudio=document.querySelector("#autoAudio"),human=document.querySelector("#human"),defaultUk=document.querySelector("#defaultUk"),defaultUs=document.querySelector("#defaultUs"),showPositionSide=document.querySelector("#showPositionSide"),showPositionNear=document.querySelector("#showPositionNear"),autoHide=document.querySelector("#autoHide"),showDuration=document.querySelector("#showDuration"),currentDuration=document.querySelector("#currentDuration"),turnOffTips=document.querySelector("#turn-off-tips"),tips=document.querySelector("#tips"),toggleKey=document.querySelector("#toggle-key"),useHttps=document.querySelector("#useHttps"),autoLearn=document.querySelector("#autoLearn"),openAPI=document.querySelector("#open-api");chrome.storage.sync.get(null,function(a){""!==a.currentWord&&queryInPopup(a.currentWord),a.linkQuery===!0?(linkQuery.checked=!0,linkQuery.nextSibling.classList.remove("unactive")):(linkQuery.checked=!1,linkQuery.nextSibling.classList.add("unactive")),a.useHttps===!0?(useHttps.checked=!0,useHttps.nextSibling.classList.remove("unactive")):(useHttps.checked=!1,useHttps.nextSibling.classList.add("unactive")),a.autoAudio===!0?(autoAudio.checked=!0,autoAudio.nextSibling.classList.remove("unactive")):(autoAudio.checked=!1,autoAudio.nextSibling.classList.add("unactive")),0===a.defaultVoice?(human.checked=!0,defaultUk.nextSibling.classList.remove("unactive"),defaultUs.nextSibling.classList.remove("unactive"),human.nextSibling.classList.add("unactive")):1===a.defaultVoice?(defaultUs.checked=!0,human.nextSibling.classList.remove("unactive"),defaultUs.nextSibling.classList.remove("unactive"),defaultUk.nextSibling.classList.add("unactive")):2===a.defaultVoice&&(defaultUs.checked=!0,human.nextSibling.classList.remove("unactive"),defaultUs.nextSibling.classList.remove("unactive"),defaultUk.nextSibling.classList.add("unactive")),"noSelect"===a.selectMode&&(noSelect.checked=!0,noSelect.nextSibling.classList.remove("unactive"),mouseSelect.nextSibling.classList.add("unactive"),useCtrl.nextSibling.classList.add("unactive"),toggleKey.disabled=!0,autoAudio.disabled=!0),"mouseSelect"===a.selectMode&&(mouseSelect.checked=!0,mouseSelect.nextSibling.classList.remove("unactive"),noSelect.nextSibling.classList.add("unactive"),useCtrl.nextSibling.classList.add("unactive"),toggleKey.disabled=!0,autoAudio.disabled=!1),"useCtrl"===a.selectMode&&(useCtrl.checked=!0,useCtrl.nextSibling.classList.remove("unactive"),noSelect.nextSibling.classList.add("unactive"),mouseSelect.nextSibling.classList.add("unactive"),toggleKey.disabled=!1,autoAudio.disabled=!1),a.showTips&&tips.classList.remove("unshow"),"side"===a.showPosition?(showPositionSide.checked=!0,showPositionSide.nextSibling.classList.remove("unactive"),showPositionNear.nextSibling.classList.add("unactive")):"near"===a.showPosition&&(showPositionNear.checked=!0,showPositionSide.nextSibling.classList.add("unactive"),showPositionNear.nextSibling.classList.remove("unactive")),"ctrl"===a.toggleKey?toggleKey.selectedIndex=0:"alt"===a.toggleKey?toggleKey.selectedIndex=1:"shift"===a.toggleKey&&(toggleKey.selectedIndex=2),"shanbay"===a.apiName?openAPI.selectedIndex=0:"xyuu"===a.apiName?openAPI.selectedIndex=1:"youdao"===a.apiName&&(openAPI.selectedIndex=2),a.autoHide===!0?(autoHide.checked=!0,autoHide.nextSibling.classList.remove("unactive"),showDuration.disabled=!1):(autoHide.checked=!1,autoHide.nextSibling.classList.add("unactive"),showDuration.disabled=!0),a.autoLearn===!0?(autoLearn.checked=!0,autoLearn.nextSibling.classList.remove("unactive")):(autoLearn.checked=!1,autoLearn.nextSibling.classList.add("unactive")),currentDuration.innerHTML=showDuration.value=a.showDuration}),linkQuery.addEventListener("click",function(a){var b=linkQuery.checked;linkQuery.nextSibling.classList.toggle("unactive"),chrome.storage.sync.set({linkQuery:b},function(){})}),useHttps.addEventListener("click",function(a){var b=useHttps.checked;useHttps.nextSibling.classList.toggle("unactive"),chrome.storage.sync.set({useHttps:b})}),autoAudio.addEventListener("click",function(a){var b=autoAudio.checked;b?autoAudio.nextSibling.classList.remove("unactive"):autoAudio.nextSibling.classList.add("unactive"),chrome.storage.sync.set({autoAudio:b},function(){})}),autoLearn.addEventListener("click",function(a){var b=autoLearn.checked;b?autoLearn.nextSibling.classList.remove("unactive"):autoLearn.nextSibling.classList.add("unactive"),chrome.storage.sync.set({autoLearn:b},function(){})}),human.addEventListener("click",function(a){human.nextSibling.classList.remove("unactive"),human.nextSibling.classList.add("unactive"),chrome.storage.sync.set({defaultVoice:0},function(){})}),defaultUk.addEventListener("click",function(a){defaultUk.nextSibling.classList.remove("unactive"),defaultUs.nextSibling.classList.add("unactive"),chrome.storage.sync.set({defaultVoice:1},function(){})}),defaultUs.addEventListener("click",function(a){defaultUs.nextSibling.classList.remove("unactive"),defaultUk.nextSibling.classList.add("unactive"),chrome.storage.sync.set({defaultVoice:2},function(){})}),turnOffTips.addEventListener("click",function(a){tips.classList.add("unshow"),chrome.storage.sync.set({showTips:!1},function(){})}),noSelect.addEventListener("click",function(a){toggleKey.disabled=!0,autoAudio.disabled=!0,noSelect.nextSibling.classList.remove("unactive"),mouseSelect.nextSibling.classList.add("unactive"),useCtrl.nextSibling.classList.add("unactive"),chrome.storage.sync.set({selectMode:"noSelect"},function(){})}),mouseSelect.addEventListener("click",function(a){toggleKey.disabled=!0,autoAudio.disabled=!1,noSelect.nextSibling.classList.add("unactive"),mouseSelect.nextSibling.classList.remove("unactive"),useCtrl.nextSibling.classList.add("unactive"),chrome.storage.sync.set({selectMode:"mouseSelect"},function(){})}),useCtrl.addEventListener("click",function(a){toggleKey.disabled&&(toggleKey.disabled=!1),autoAudio.disabled=!1,noSelect.nextSibling.classList.add("unactive"),mouseSelect.nextSibling.classList.add("unactive"),useCtrl.nextSibling.classList.remove("unactive"),chrome.storage.sync.set({selectMode:"useCtrl"},function(){})}),showPositionSide.addEventListener("click",function(a){showPositionSide.nextSibling.classList.remove("unactive"),showPositionNear.nextSibling.classList.add("unactive"),chrome.storage.sync.set({showPosition:"side"},function(){})}),showPositionNear.addEventListener("click",function(a){showPositionSide.nextSibling.classList.add("unactive"),showPositionNear.nextSibling.classList.remove("unactive"),chrome.storage.sync.set({showPosition:"near"},function(){})}),autoHide.addEventListener("click",function(a){var b=autoHide.checked;b?(autoHide.nextSibling.classList.remove("unactive"),showDuration.disabled=!1):(autoHide.nextSibling.classList.add("unactive"),showDuration.disabled=!0),chrome.storage.sync.set({autoHide:b},function(){})}),showDuration.addEventListener("input",function(a){currentDuration.innerHTML=showDuration.value,chrome.storage.sync.set({showDuration:showDuration.value},function(){})}),toggleKey.onchange=function(a){chrome.storage.sync.set({toggleKey:this.value},function(){})},openAPI.onchange=function(a){chrome.storage.sync.set({apiName:this.value},function(){})}; \ No newline at end of file diff --git a/public/js/selection.min.js b/public/js/selection.min.js index 56ab3a8..334c369 100644 --- a/public/js/selection.min.js +++ b/public/js/selection.min.js @@ -1 +1 @@ -!function(){function a(a){var b=a.getAttribute("data-src"),c=document.createElement("audio");c.setAttribute("src",b+"&type="+e.defaultVoice),a.appendChild(c),e.autoAudio===!0&&c.play(),c.addEventListener("ended",function(){this.load()}),a.addEventListener("click",function(){c.play()})}function b(a,b){return a.top===b.top&&a.bottom===b.bottom&&a.left===b.left&&a.right===b.right?!0:!1}var c,d={top:0,bottom:0,left:0,right:0,again:0},e={};chrome.storage.sync.get(null,function(a){for(var b in a)e[b]=a[b]}),chrome.storage.onChanged.addListener(function(a){void 0!==a.linkQuery&&(e.linkQuery=a.linkQuery.newValue),void 0!==a.useHttps&&(e.useHttps=a.useHttps.newValue),void 0!==a.autoAudio&&(e.autoAudio=a.autoAudio.newValue),void 0!==a.defaultVoice&&(e.defaultVoice=a.defaultVoice.newValue),void 0!==a.selectMode&&(e.selectMode=a.selectMode.newValue),void 0!==a.toggleKey&&(e.toggleKey=a.toggleKey.newValue),void 0!==a.autoHide&&(e.autoHide=a.autoHide.newValue),void 0!==a.showDuration&&(e.showDuration=a.showDuration.newValue),void 0!==a.showPosition&&(e.showPosition=a.showPosition.newValue)});var f=function(a){var c=window.getSelection&&window.getSelection();if(c&&c.rangeCount>0){var f=trim(c.toString()),i=c.getRangeAt(0).getBoundingClientRect();if(b(i,d)&&d.again)return void(d.again=0);if(""===f||!/^[^\u4e00-\u9fa5]+$/.test(f))return;for(var j=document.documentElement.querySelectorAll(".ChaZD-result-container"),k=0,l=j.length;l>k;k++)if(j[k].getAttribute("data-text").toLowerCase()===f.toLowerCase())return;chrome.storage.sync.set({currentWord:f},function(){});for(var m in d)d[m]="again"==m?1:i[m];"side"===e.showPosition&&g(f,e.useHttps),"near"===e.showPosition&&h(f,e.useHttps,i,a)}},g=function(a,b){var d=j(a,b);d.classList.add("ChaZD-result-side"),document.documentElement.appendChild(d),e.autoHide&&(c=setTimeout(function(){document.querySelector(".ChaZD-result-container")&&document.documentElement.removeChild(d)},1e3*e.showDuration))},h=function(a,b,d,f){var g=j(a,b),h=i();document.documentElement.appendChild(g),document.documentElement.appendChild(h);var k={};0===d.left&&0===d.top&&(d={left:f.clientX,top:f.clientY,height:15});var l=g.offsetWidth,m=d.right-d.left,n=d.left+window.pageXOffset,o=d.top+window.pageYOffset,p=m/2+n,q=n-(l-m)/2,r=p-12;qwindow.pageXOffset+document.documentElement.clientWidth&&(q=window.pageXOffset+document.documentElement.clientWidth-l);var s=0;if(s=document.documentElement.clientHeight>document.body.clientHeight?document.body.clientHeight:document.documentElement.clientHeight,0===s&&(s=document.documentElement.clientHeight),d.top>=150){var t=s-o+10,u=t+1;k={left:q,bottom:t,arrowLeft:r,arrowBottom:u}}else k={left:q,top:o+d.height+12,arrowLeft:r,arrowTop:o+d.height+1};g.style.left=k.left+"px",h.style.left=k.arrowLeft+"px";var v,w,x=document.querySelectorAll(".ChaZD-arrow-outer"),y=document.querySelectorAll(".ChaZD-arrow-inner");if(k.bottom)for(g.style.bottom=k.bottom+"px",h.style.bottom=k.arrowBottom+"px",v=0,w=x.length;w>v;v++)x[v].classList.add("ChaZD-arrow-outer-down"),y[v].classList.add("ChaZD-arrow-inner-down");if(k.top)for(g.style.top=k.top+"px",h.style.top=k.arrowTop+"px",v=0,w=x.length;w>v;v++)x[v].classList.add("ChaZD-arrow-outer-up"),y[v].classList.add("ChaZD-arrow-inner-up");e.autoHide&&(c=setTimeout(function(){document.querySelector(".ChaZD-result-container")&&document.querySelector(".ChaZD-arrow-main")&&(document.documentElement.removeChild(g),document.documentElement.removeChild(h))},1e3*e.showDuration))},i=function(){var a=document.createElement("div");a.classList.add("ChaZD-arrow-main");var b=document.createElement("div");b.setAttribute("class","ChaZD-arrow-outer");var c=document.createElement("div");return c.setAttribute("class","ChaZD-arrow-inner"),a.appendChild(b),a.appendChild(c),a},j=function(b,c){var d=document.createElement("div");d.classList.add("ChaZD-result-container"),d.setAttribute("data-text",b);var e=document.createElement("div");return e.setAttribute("id","ChaZD-searching"),e.innerHTML="ψ(._. )>划词君正在翻译。。。",d.appendChild(e),chrome.runtime.sendMessage({queryWord:b,source:"select",useHttps:c},function(b){var c=b;if(e.innerHTML="","query success"===c.validMessage){d.innerHTML=c.titleBlock;var f=d.querySelector(".voice-container");a(f);var g=document.createElement("div");c.basicBlock?(g.innerHTML=c.basicBlock,d.appendChild(g)):c.haveTranslation?d.querySelector(".title-translation").style.display="block":c.haveWebTranslation?(g.innerHTML=c.webBlock,d.appendChild(g),d.querySelector(".web-title").innerHTML="网络释义"):d.innerHTML="╮(╯▽╰)╭划词君无能为力啊
还是右键问问谷歌君吧=>"}else d.innerHTML=20==c.errorCode?"

这段文字太长,词典君无能为力了(┬_┬)

试试短一点的吧~

":40==c.errorCode?"

对不起,这段文字太高深了,请饶过词典君吧(┬_┬)

":"

词典君罢工啦(┬_┬)

是不是网络不太好?

稍后再试一次吧

"}),d},k=["ChaZD-result-container","title-container","title-word","title-translation","basic-container","phonetic-container","explains-container","explains-container","explains-list","property-container","explains-item","voice-container","us-phonetic-container","uk-phonetic-container","web-explains-container","web-explains-list","web-key","explains-item-value","web-value"];document.documentElement.addEventListener("mousedown",function(a){for(var b in k)if(a.target.classList.contains(k[b]))return;clearTimeout(c);var d,e,f=document.querySelectorAll(".ChaZD-result-container"),g=document.querySelectorAll(".ChaZD-arrow-main");if(f)for(d=0,e=f.length;e>d;d++)document.documentElement.removeChild(f[d]);if(g)for(d=0,e=g.length;e>d;d++)document.documentElement.removeChild(g[d]);chrome.storage.sync.set({currentWord:""})}),window.addEventListener("resize",function(){var a=document.querySelector(".ChaZD-result-container"),b=document.querySelector(".ChaZD-arrow-main");a&&document.documentElement.removeChild(a),b&&document.documentElement.removeChild(b)});var l=function(a){if("noSelect"!==e.selectMode){if("useCtrl"===e.selectMode)if("ctrl"===e.toggleKey){if(!a.ctrlKey&&!a.metaKey)return void(d.again=0)}else if("alt"===e.toggleKey){if(!a.altKey)return void(d.again=0)}else if("shift"===e.toggleKey&&!a.shiftKey)return void(d.again=0);f(a)}},m=null,n=function(a){e.linkQuery&&(m=a.target,a.shiftKey&&p(a))},o=function(a){e.linkQuery&&(m&&m.classList.contains("ChaZD-link")&&q(a,!0),m=null)},p=function(a){m&&a.shiftKey&&(r(a),m.setAttribute("ChaZD-href",m.getAttribute("href")),m.removeAttribute("href"),m.classList.add("ChaZD-link"))},q=function(a,b){m&&(b||16==a.keyCode)&&(m.setAttribute("href",m.getAttribute("ChaZD-href")),m.removeAttribute("ChaZD-href"),m.classList.remove("ChaZD-link"))},r=function(a){e.linkQuery&&a.shiftKey&&window.getSelection().empty()};document.documentElement.addEventListener("mouseup",l),document.documentElement.addEventListener("mouseover",function(a){("A"===a.target.nodeName||"a"===a.target.nodeName)&&n(a)}),document.documentElement.addEventListener("mouseout",function(a){("A"===a.target.nodeName||"a"===a.target.nodeName)&&o(a)}),document.documentElement.addEventListener("keydown",p),document.documentElement.addEventListener("keyup",q),document.documentElement.addEventListener("selectstart",l)}(); \ No newline at end of file +!function(){function a(a,b){return a.top===b.top&&a.bottom===b.bottom&&a.left===b.left&&a.right===b.right?!0:!1}var b,c={top:0,bottom:0,left:0,right:0,again:0},d=function(b){var d=window.getSelection&&window.getSelection();if(d&&d.rangeCount>0){var g=trim(d.toString()),h=d.getRangeAt(0).getBoundingClientRect();if(a(h,c)&&c.again)return void(c.again=0);if(""===g||!/^[^\u4e00-\u9fa5]+$/.test(g))return;for(var i=document.documentElement.querySelectorAll(".ChaZD-result-container"),j=0,k=i.length;k>j;j++)if(i[j].getAttribute("data-text").toLowerCase()===g.toLowerCase())return;chrome.storage.sync.set({currentWord:g},function(){});for(var l in c)"again"==l?c[l]=1:c[l]=h[l];"side"===currentSettings.showPosition&&e(g,currentSettings.useHttps),"near"===currentSettings.showPosition&&f(g,currentSettings.useHttps,h,b)}},e=function(a,c){var d=h(a,c);d.classList.add("ChaZD-result-side"),document.documentElement.appendChild(d),currentSettings.autoHide&&(b=setTimeout(function(){document.querySelector(".ChaZD-result-container")&&document.documentElement.removeChild(d)},1e3*currentSettings.showDuration))},f=function(a,c,d,e){var f=h(a,c),i=g();document.documentElement.appendChild(f),document.documentElement.appendChild(i);var j={};0===d.left&&0===d.top&&(d={left:e.clientX,top:e.clientY,height:15});var k=f.offsetWidth,l=d.right-d.left,m=d.left+window.pageXOffset,n=d.top+window.pageYOffset,o=l/2+m,p=m-(k-l)/2,q=o-12;pwindow.pageXOffset+document.documentElement.clientWidth&&(p=window.pageXOffset+document.documentElement.clientWidth-k);var r=0;if(r=document.documentElement.clientHeight>document.body.clientHeight?document.body.clientHeight:document.documentElement.clientHeight,0===r&&(r=document.documentElement.clientHeight),d.top>=150){var s=r-n+10,t=s+1;j={left:p,bottom:s,arrowLeft:q,arrowBottom:t}}else j={left:p,top:n+d.height+12,arrowLeft:q,arrowTop:n+d.height+1};f.style.left=j.left+"px",i.style.left=j.arrowLeft+"px";var u,v,w=document.querySelectorAll(".ChaZD-arrow-outer"),x=document.querySelectorAll(".ChaZD-arrow-inner");if(j.bottom)for(f.style.bottom=j.bottom+"px",i.style.bottom=j.arrowBottom+"px",u=0,v=w.length;v>u;u++)w[u].classList.add("ChaZD-arrow-outer-down"),x[u].classList.add("ChaZD-arrow-inner-down");if(j.top)for(f.style.top=j.top+"px",i.style.top=j.arrowTop+"px",u=0,v=w.length;v>u;u++)w[u].classList.add("ChaZD-arrow-outer-up"),x[u].classList.add("ChaZD-arrow-inner-up");currentSettings.autoHide&&(b=setTimeout(function(){document.querySelector(".ChaZD-result-container")&&document.querySelector(".ChaZD-arrow-main")&&(document.documentElement.removeChild(f),document.documentElement.removeChild(i))},1e3*currentSettings.showDuration))},g=function(){var a=document.createElement("div");a.classList.add("ChaZD-arrow-main");var b=document.createElement("div");b.setAttribute("class","ChaZD-arrow-outer");var c=document.createElement("div");return c.setAttribute("class","ChaZD-arrow-inner"),a.appendChild(b),a.appendChild(c),a},h=function(a,b){var c=document.createElement("div");c.classList.add("ChaZD-result-container"),c.setAttribute("data-text",a);var d=document.createElement("div");return d.setAttribute("id","ChaZD-searching"),d.innerHTML="ψ(._. )>划词君正在翻译。。。",c.appendChild(d),chrome.runtime.sendMessage({queryWord:a,source:"select"},function(a){var b=a;if(d.innerHTML="",0===b.Code){c.innerHTML=b.titleBlock;var e=c.querySelector(".voice-container"),f=function(a){var b=a.getAttribute("data-src"),c=document.createElement("audio");currentSettings.defaultVoice&&(b+="&type="+currentSettings.defaultVoice),c.setAttribute("src",b),a.appendChild(c),currentSettings.autoAudio===!0&&c.play(),c.addEventListener("ended",function(a){this.load()}),a.addEventListener("click",function(a){c.play()})};f(e);var g=document.createElement("div");b.basicBlock?(g.innerHTML=b.basicBlock,c.appendChild(g)):b.haveTranslation?c.querySelector(".title-translation").style.display="block":b.haveWebTranslation?(g.innerHTML=b.webBlock,c.appendChild(g),c.querySelector(".web-title").innerHTML="网络释义"):c.innerHTML="╮(╯▽╰)╭划词君无能为力啊
还是右键问问谷歌君吧=>"}else 20==b.Code?c.innerHTML="

这段文字太长,词典君无能为力了(┬_┬)

试试短一点的吧~

":40==b.Code?c.innerHTML="

对不起,这段文字太高深了,请饶过词典君吧(┬_┬)

":c.innerHTML="

词典君罢工啦(┬_┬)

是不是网络不太好?

稍后再试一次吧

"}),c},i=["ChaZD-result-container","title-container","title-word","title-translation","basic-container","phonetic-container","explains-container","explains-container","explains-list","property-container","explains-item","voice-container","us-phonetic-container","uk-phonetic-container","web-explains-container","web-explains-list","web-key","explains-item-value","web-value"];document.documentElement.addEventListener("mousedown",function(a){for(var c in i)if(a.target.classList.contains(i[c]))return;clearTimeout(b);var d,e,f=document.querySelectorAll(".ChaZD-result-container"),g=document.querySelectorAll(".ChaZD-arrow-main");if(f)for(d=0,e=f.length;e>d;d++)document.documentElement.removeChild(f[d]);if(g)for(d=0,e=g.length;e>d;d++)document.documentElement.removeChild(g[d]);chrome.storage.sync.set({currentWord:""})}),window.addEventListener("resize",function(a){var b=document.querySelector(".ChaZD-result-container"),c=document.querySelector(".ChaZD-arrow-main");b&&document.documentElement.removeChild(b),c&&document.documentElement.removeChild(c)});var j=function(a){if("noSelect"!==currentSettings.selectMode){if("useCtrl"===currentSettings.selectMode)if("ctrl"===currentSettings.toggleKey){if(!a.ctrlKey&&!a.metaKey)return void(c.again=0)}else if("alt"===currentSettings.toggleKey){if(!a.altKey)return void(c.again=0)}else if("shift"===currentSettings.toggleKey&&!a.shiftKey)return void(c.again=0);d(a)}},k=null,l=function(a){currentSettings.linkQuery&&(k=a.target,a.shiftKey&&n(a))},m=function(a){currentSettings.linkQuery&&(k&&k.classList.contains("ChaZD-link")&&o(a,!0),k=null)},n=function(a){k&&a.shiftKey&&(p(a),k.setAttribute("ChaZD-href",k.getAttribute("href")),k.removeAttribute("href"),k.classList.add("ChaZD-link"))},o=function(a,b){k&&(b||16==a.keyCode)&&(k.setAttribute("href",k.getAttribute("ChaZD-href")),k.removeAttribute("ChaZD-href"),k.classList.remove("ChaZD-link"))},p=function(a){currentSettings.linkQuery&&a.shiftKey&&window.getSelection().empty()};document.documentElement.addEventListener("mouseup",j),document.documentElement.addEventListener("mouseover",function(a){("A"===a.target.nodeName||"a"===a.target.nodeName)&&l(a)}),document.documentElement.addEventListener("mouseout",function(a){("A"===a.target.nodeName||"a"===a.target.nodeName)&&m(a)}),document.documentElement.addEventListener("keydown",n),document.documentElement.addEventListener("keyup",o),document.documentElement.addEventListener("selectstart",j)}(); \ No newline at end of file diff --git a/public/js/utility.min.js b/public/js/utility.min.js index fb70afe..201ebda 100644 --- a/public/js/utility.min.js +++ b/public/js/utility.min.js @@ -1 +1 @@ -function isEmpty(a){for(var b in a)return!1;return!0}function fmt(){var a=arguments;return a[0].replace(/#{(.*?)}/g,function(b,c){return function(a,b){var c=/\d+/.test(b[0])?parseInt(b[0]):b[0];return b.length>1?arguments.callee(a[c],b.slice(1)):a[c]}("object"==typeof a[1]?a[1]:a,c.split(/\.|\[|\]\[|\]\./))})}function trim(a){return a.replace(/(^\s*)|(\s*$)/g,"")}var api={key:1116151381,keyfrom:"youdaocidian"},urls={dict:"http://fanyi.youdao.com/openapi.do?keyfrom="+api.keyfrom+"&key="+api.key+"&type=data&doctype=json&version=1.1&q=",voice:"http://dict.youdao.com/dictvoice?audio=",dictHttps:"https://fanyi.youdao.com/openapi.do?keyfrom="+api.keyfrom+"&key="+api.key+"&type=data&doctype=json&version=1.1&q=",voiceHttps:"https://dict.youdao.com/dictvoice?audio="},settings={selectMode:"mouseSelect",showPosition:"near",toggleKey:"ctrl",showTips:!0,currentWord:"",linkQuery:!1,autoAudio:!1,autoHide:!1,showDuration:3,defaultVoice:1,useHttps:!1},frame={titleContainer:'
#{1}#{2}
',titleWord:'
#{1}#{2}
',voiceContainer:'
',titleTranslation:'
#{1}
',basicContainer:'
#{1}#{2}
',phoneticContainer:'
#{1}#{2}
',ukPhoneticContainer:'
#{1}
',usPhoneticContainer:'
#{1}
',explainsContainer:'
#{1}
',explainsList:'
    #{1}
',explain:'
  • #{1}#{2}
  • ',propertyContainer:'#{2}',webExplainsContainer:'
    网络释义及短语
    #{1}
    ',webExplainsList:'
      #{1}
    ',webExplain:'
  • #{1}#{2}
  • '}; \ No newline at end of file +function ajax(a,b,c,d,e){var f=new XMLHttpRequest;f.open(a,b,!0),f.onreadystatechange=function(){4==f.readyState&&d(f)},void 0!=e&&e(f),f.send(c)}function isEmpty(a){for(var b in a)return!1;return!0}function fmt(){var a=arguments;return a[0].replace(/#{(.*?)}/g,function(b,c){return function(a,b){var c=/\d+/.test(b[0])?parseInt(b[0]):b[0];return b.length>1?arguments.callee(a[c],b.slice(1)):a[c]}("object"==typeof a[1]?a[1]:a,c.split(/\.|\[|\]\[|\]\./))})}function trim(a){return a.replace(/(^\s*)|(\s*$)/g,"")}var settings={selectMode:"mouseSelect",showPosition:"near",toggleKey:"ctrl",showTips:!0,currentWord:"",linkQuery:!1,autoAudio:!1,autoHide:!1,showDuration:3,defaultVoice:0,useHttps:!1,autoLearn:!0,apiName:"shanbay"},currentSettings=settings;chrome.storage.sync.get(null,function(a){for(var b in a)currentSettings[b]=a[b]}),chrome.storage.onChanged.addListener(function(a){void 0!==a.linkQuery&&(currentSettings.linkQuery=a.linkQuery.newValue),void 0!==a.useHttps&&(currentSettings.useHttps=a.useHttps.newValue),void 0!==a.autoAudio&&(currentSettings.autoAudio=a.autoAudio.newValue),void 0!==a.defaultVoice&&(currentSettings.defaultVoice=a.defaultVoice.newValue),void 0!==a.selectMode&&(currentSettings.selectMode=a.selectMode.newValue),void 0!==a.toggleKey&&(currentSettings.toggleKey=a.toggleKey.newValue),void 0!==a.autoHide&&(currentSettings.autoHide=a.autoHide.newValue),void 0!==a.showDuration&&(currentSettings.showDuration=a.showDuration.newValue),void 0!==a.showPosition&&(currentSettings.showPosition=a.showPosition.newValue),void 0!==a.autoLearn&&(currentSettings.autoLearn=a.autoLearn.newValue),void 0!==a.apiName&&(currentSettings.apiName=a.apiName.newValue)});var frame={titleContainer:'
    #{1}#{2}
    ',titleWord:'
    #{1}#{2}
    ',voiceContainer:'
    ',titleTranslation:'
    #{1}
    ',basicContainer:'
    #{1}#{2}
    ',phoneticContainer:'
    #{1}#{2}
    ',ukPhoneticContainer:'
    #{1}
    ',usPhoneticContainer:'
    #{1}
    ',explainsContainer:'
    #{1}
    ',explainsList:'
      #{1}
    ',explain:'
  • #{1}#{2}
  • ',propertyContainer:'#{2}',webExplainsContainer:'
    网络释义及短语
    #{1}
    ',webExplainsList:'
      #{1}
    ',webExplain:'
  • #{1}#{2}
  • '},youdao=function(){var a={key:1116151381,keyfrom:"youdaocidian"},b={dict:"http://fanyi.youdao.com/openapi.do?keyfrom="+a.keyfrom+"&key="+a.key+"&type=data&doctype=json&version=1.1&q=",voice:"http://dict.youdao.com/dictvoice?audio=",dictHttps:"https://fanyi.youdao.com/openapi.do?keyfrom="+a.keyfrom+"&key="+a.key+"&type=data&doctype=json&version=1.1&q=",voiceHttps:"https://dict.youdao.com/dictvoice?audio="},c=this;c.initVoice=function(a,b){var c="";return c=1===b?"英音":2===b?"美音":"真人发音",fmt(frame.voiceContainer,a,c)},c.checkCode=function(a){var b={message:"",error:0,Code:0};switch(a){case 0:b.Message="查询成功";break;case 20:b.Message="要翻译的文本过长",b.error=1,b.Code=20;break;case 30:b.Message="无法进行有效的翻译",b.error=1,b.Code=30;break;case 40:b.Message="不支持的语言类型",b.error=1,b.Code=40;break;case 50:b.Message="无效的key",b.error=1,b.Code=50;break;case 60:b.Message="无辞典结果",b.error=1,b.Code=60}return b},c.shortWord=function(a){return a.slice(0,a.lastIndexOf(" ",50)).concat(" ...")},c.getVoice=function(a,c){var d=(currentSettings.useHttps?b.voiceHttps:b.voice)+a.query;return void 0!==c&&(d=d+"&type="+c),d},c.initTitle=function(a){var b=a.translation,d=a.query,e=c.initVoice(c.getVoice(a));d=d.length>=50&&"select"==c.wordSource?c.shortWord(d):d;var f=fmt(frame.titleWord,d,e),g=b?fmt(frame.titleTranslation,b.toString()):"";return{titleBlock:fmt(frame.titleContainer,f,g,d.length>=50?"long-text":"")}},c.haveTranslation=function(a){if(c.checkCode(a.errorCode).error||!b)return!1;var b=a.translation,d=a.query;return trim(d.toLowerCase())===trim(b.toString().toLowerCase())?!1:!0},c.parseBasicPhonetic=function(a){var b=a.basic,d=b["uk-phonetic"],e=b["us-phonetic"];if(void 0!==d&&void 0!==e){var f=c.initVoice(c.getVoice(a,1),1),g=fmt(frame.ukPhoneticContainer,"["+d+"]"+f),h=c.initVoice(c.getVoice(a,2),2),i=fmt(frame.usPhoneticContainer,"["+e+"]"+h);return fmt(frame.phoneticContainer,g,i)}return fmt(frame.phoneticContainer,"","")},c.parseProperty=function(a){var b="";switch(a){case"adj.":b="形容词";break;case"adv.":b="副词";break;case"n.":b="名词";break;case"vi.":b="不及物动词";break;case"vt.":b="及物动词";break;case"prep.":b="介词";break;case"conj.":b="连词";break;case"int.":b="感叹词";break;case"abbr.":b="代词";break;case"pron.":b=""}return b},c.parseBasicExplains=function(a){var b,d=a.basic,e=d.explains,f="";for(b=0;b= 50 && this.wordSource == "select" ? this.shortWord(queryWord) : queryWord; - - //console.log("word:", queryWord); - var titleWord = fmt(frame.titleWord, queryWord, voiceContainer); - var titleTranslation = fmt(frame.titleTranslation, translation.toString()); - - - return { - titleBlock : fmt(frame.titleContainer, titleWord, titleTranslation, queryWord.length >=50 ? "long-text" : ""), - //haveTranslation : haveTranslation - }; -}; - -ChaZD.prototype.shortWord = function (longWord) { - return longWord.slice(0, longWord.lastIndexOf(" ", 50)).concat(" ..."); -}; - -ChaZD.prototype.parseBasicResult = function (result) { - var basic = result.basic; - var queryWord = result.query; - - var phoneticBlock = this.parseBasicPhonetic(basic, queryWord); - var explainsBlock = this.parseBasicExplains(basic, queryWord); - - var basicContainer = fmt(frame.basicContainer, phoneticBlock, explainsBlock); - return basicContainer; -}; - -ChaZD.prototype.parseBasicPhonetic = function (basic, queryWord) { - var ukPhonetic = basic["uk-phonetic"]; - var usPhonetic = basic["us-phonetic"]; - - if (ukPhonetic !== undefined && usPhonetic !== undefined) { - var ukVoice = this.initVoice(queryWord, 1); - var ukPhoneticContainer = fmt(frame.ukPhoneticContainer, "[" + ukPhonetic + "]" + ukVoice); - - var usVoice = this.initVoice(queryWord, 2); - var usPhoneticContainer = fmt(frame.usPhoneticContainer, "[" + usPhonetic + "]" + usVoice); - - return fmt(frame.phoneticContainer, ukPhoneticContainer, usPhoneticContainer); - } - - return fmt(frame.phoneticContainer, "", ""); -}; - -ChaZD.prototype.initVoice = function (queryWord, type) { - var src = (this.useHttps ? urls.voiceHttps : urls.voice) + queryWord; - if(type !== undefined) { - src = src + "&type=" + type; - } - var title = ""; - if(type === 1){ - title = "英音"; - } else if (type === 2){ - title = "美音"; - } else { - title = "真人发音"; - } - - return fmt(frame.voiceContainer, src, title); -}; - -ChaZD.prototype.parseBasicExplains = function (basic, queryWord) { - var explains = basic.explains; - var i; - var explainsContent = ""; - for (i = 0; i < explains.length; i++) { - var currentExplain = explains[i]; - - var haveProperty = currentExplain.indexOf(". "); - var property = (haveProperty !== -1) ? currentExplain.slice(0, haveProperty + 1) : ""; - var propertyTitle = this.parseProperty(property); - var propertyContainer = fmt(frame.propertyContainer, propertyTitle, property); - var explainText = (haveProperty !== -1) ? currentExplain.slice(haveProperty + 1) : currentExplain; - - var explain = fmt(frame.explain, propertyContainer, explainText); - explainsContent += explain; - } - - return fmt(frame.explainsContainer, fmt(frame.explainsList, explainsContent)); -}; - -ChaZD.prototype.parseProperty = function (property) { - var propertyText = ""; - switch (property) { - case "adj." : - propertyText = "形容词"; - break; - case "adv." : - propertyText = "副词"; - break; - case "n." : - propertyText = "名词"; - break; - case "vi." : - propertyText = "不及物动词"; - break; - case "vt." : - propertyText = "及物动词"; - break; - case "prep." : - propertyText = "介词"; - break; - case "conj." : - propertyText = "连词"; - break; - case "int." : - propertyText = "感叹词"; - break; - case "abbr." : - propertyText = "代词"; - break; - case "pron." : - propertyText = ""; - break; - default : - } - - return propertyText; -}; - - - -ChaZD.prototype.parseWebResult = function (result) { - var web = result.web; - var webExplainsContent = ""; - var i; - for (i = 0; i < web.length ; i++) { - var webExplain = fmt(frame.webExplain, web[i].key, web[i].value); - webExplainsContent += webExplain; - } - - return fmt(frame.webExplainsContainer, fmt(frame.webExplainsList, webExplainsContent)); -}; - //字符串预处理,解析驼峰命名法和下划线命名法的单词、词组 function preprocessWord (originWord) { if (originWord.indexOf(" ") === -1) { @@ -344,9 +93,7 @@ chrome.storage.sync.get(null,function (items) { chrome.runtime.onMessage.addListener( function (message, sender, sendResponse) { - //console.log("message from sender:" + JSON.stringify(message)); - //console.log("sender is " + JSON.stringify(sender)); - new ChaZD(preprocessWord(message.queryWord), message.useHttps, message.source, sendResponse); - + var a = new api[currentSettings.apiName](); + a.Query(preprocessWord(message.queryWord), message.source, sendResponse); return true; }); diff --git a/src/javascript/popup.js b/src/javascript/popup.js index f2ae91a..5dcd5e5 100644 --- a/src/javascript/popup.js +++ b/src/javascript/popup.js @@ -23,10 +23,10 @@ function queryInPopup(queryText) { //console.log("quertText: " + queryText); if (queryText) { $input.value = queryText; - chrome.extension.sendMessage({queryWord: queryText, source: "popup", useHttps: useHttpsValue}, buildResult); + chrome.extension.sendMessage({queryWord: queryText, source: "popup"}, buildResult); } else { - chrome.extension.sendMessage({queryWord: $input.value, source: "popup", useHttps: useHttpsValue}, buildResult); + chrome.extension.sendMessage({queryWord: $input.value, source: "popup"}, buildResult); } } @@ -34,7 +34,7 @@ var buildResult = function(response) { //alert("response from xhr: " + JSON.stringify(response)); var resultObj = response; var resultBlock = ""; - if (resultObj.validMessage == "query success") { + if (resultObj.Code === 0) { resultBlock += resultObj.titleBlock; if (resultObj.basicBlock !== undefined) { resultBlock += resultObj.basicBlock; @@ -44,15 +44,26 @@ var buildResult = function(response) { } $queryResultContainer.innerHTML = resultBlock; var voiceCollection = document.querySelectorAll(".voice-container"); - //console.log("voiceCollection length: " + voiceCollection.length); + var buildVoice = function (voice) { + var src = voice.getAttribute("data-src"); + var audioBlock = document.createElement("audio"); + audioBlock.setAttribute("src", src); + voice.appendChild(audioBlock); + audioBlock.addEventListener("ended", function (event) { + this.load(); + }); + voice.addEventListener("click", function (event) { + audioBlock.play(); + }); + }; var i, len; for (i = 0, len = voiceCollection.length; i < len; i++) { buildVoice(voiceCollection[i]); } } else { - if (resultObj.errorCode == 20) { + if (resultObj.Code == 20) { $queryResultContainer.innerHTML = "

    这段文字太长,词典君无能为力了(┬_┬)

    试试短一点的吧~

    "; - } else if (resultObj.errorCode == 40) { + } else if (resultObj.Code == 40) { $queryResultContainer.innerHTML = "

    对不起,这段文字太高深了,请饶过词典君吧(┬_┬)

    "; } else { $queryResultContainer.innerHTML = "

    词典君罢工啦(┬_┬)

    是不是网络不太好?

    稍后再试一次吧

    "; @@ -75,23 +86,6 @@ $input.addEventListener("input", function (event) { }, 500); }); -function buildVoice(voice) { - var src = voice.getAttribute("data-src"); - //console.log("voice src: [] " + src); - var audioBlock = document.createElement("audio"); - audioBlock.setAttribute("src", src); - voice.appendChild(audioBlock); - audioBlock.addEventListener("ended", function (event) { - //console.log("loading src: " + this.getAttribute("src")); - this.load(); - }); - voice.addEventListener("click", function (event) { - //console.log("playing src: " + audioBlock.getAttribute("src")); - audioBlock.play(); - }); -} - - function createLink(link, url) { link.addEventListener("click", function (event) { chrome.tabs.create({"url": url}); @@ -130,12 +124,13 @@ function totalHeight(className) { return sum + 10; } -var blockHeight = totalHeight("top-menu") + totalHeight("sub-menu") + totalHeight("carved") + 32; +var blockHeight = totalHeight("top-menu") + totalHeight("sub-menu") + totalHeight("carved") + 52; var linkQuery = document.querySelector("#linkQuery"); var noSelect = document.querySelector("#noSelect"); var mouseSelect = document.querySelector("#mouseSelect"); var useCtrl = document.querySelector("#useCtrl"); var autoAudio = document.querySelector("#autoAudio"); +var human = document.querySelector("#human"); var defaultUk = document.querySelector("#defaultUk"); var defaultUs = document.querySelector("#defaultUs"); var showPositionSide = document.querySelector("#showPositionSide"); @@ -147,7 +142,8 @@ var turnOffTips = document.querySelector("#turn-off-tips"); var tips = document.querySelector("#tips"); var toggleKey = document.querySelector("#toggle-key"); var useHttps = document.querySelector("#useHttps"); -var useHttpsValue = false; +var autoLearn = document.querySelector("#autoLearn"); +var openAPI = document.querySelector("#open-api"); chrome.storage.sync.get(null, function (items) { if(items.currentWord !== "") { @@ -162,11 +158,9 @@ chrome.storage.sync.get(null, function (items) { } if(items.useHttps === true) { useHttps.checked = true; - useHttpsValue = true; useHttps.nextSibling.classList.remove("unactive"); } else { useHttps.checked = false; - useHttpsValue = false; useHttps.nextSibling.classList.add("unactive"); } if(items.autoAudio === true) { @@ -176,12 +170,19 @@ chrome.storage.sync.get(null, function (items) { autoAudio.checked = false; autoAudio.nextSibling.classList.add("unactive"); } - if(items.defaultVoice === 1) { - defaultUk.checked = true; + if(items.defaultVoice === 0) { + human.checked = true; defaultUk.nextSibling.classList.remove("unactive"); - defaultUs.nextSibling.classList.add("unactive"); - } else if (items.defaultVoice === 2) { + defaultUs.nextSibling.classList.remove("unactive"); + human.nextSibling.classList.add("unactive"); + }else if (items.defaultVoice === 1) { defaultUs.checked = true; + human.nextSibling.classList.remove("unactive"); + defaultUs.nextSibling.classList.remove("unactive"); + defaultUk.nextSibling.classList.add("unactive"); + }else if (items.defaultVoice === 2) { + defaultUs.checked = true; + human.nextSibling.classList.remove("unactive"); defaultUs.nextSibling.classList.remove("unactive"); defaultUk.nextSibling.classList.add("unactive"); } @@ -231,6 +232,13 @@ chrome.storage.sync.get(null, function (items) { } else if (items.toggleKey === "shift") { toggleKey.selectedIndex = 2; } + if (items.apiName === "shanbay") { + openAPI.selectedIndex = 0; + } else if (items.apiName === "xyuu") { + openAPI.selectedIndex = 1; + } else if (items.apiName === "youdao") { + openAPI.selectedIndex = 2; + } if (items.autoHide === true) { autoHide.checked = true; autoHide.nextSibling.classList.remove("unactive"); @@ -240,6 +248,13 @@ chrome.storage.sync.get(null, function (items) { autoHide.nextSibling.classList.add("unactive"); showDuration.disabled = true; } + if(items.autoLearn === true) { + autoLearn.checked = true; + autoLearn.nextSibling.classList.remove("unactive"); + } else { + autoLearn.checked = false; + autoLearn.nextSibling.classList.add("unactive"); + } currentDuration.innerHTML = showDuration.value = items.showDuration; }); @@ -268,6 +283,26 @@ autoAudio.addEventListener("click", function (event) { //console.log("[ChaZD] Success update settings autoAudio = " + currentAutoAudio); }); }); +//自动加入生词本 +autoLearn.addEventListener("click", function (event) { + var currentAutoLearn = autoLearn.checked; + if (currentAutoLearn) { + autoLearn.nextSibling.classList.remove("unactive"); + } else { + autoLearn.nextSibling.classList.add("unactive"); + } + chrome.storage.sync.set({"autoLearn": currentAutoLearn}, function() { + //console.log("[ChaZD] Success update settings autoLearn = " + currentAutoLearn); + }); +}); + +human.addEventListener("click", function (event) { + human.nextSibling.classList.remove("unactive"); + human.nextSibling.classList.add("unactive"); + chrome.storage.sync.set({"defaultVoice": 0}, function() { + //console.log("[ChaZD] Success update settings defaultVoice = 1"); + }); +}); defaultUk.addEventListener("click", function (event) { defaultUk.nextSibling.classList.remove("unactive"); @@ -373,6 +408,11 @@ toggleKey.onchange = function (event) { }); }; +openAPI.onchange = function (event) { + chrome.storage.sync.set({"apiName" : this.value}, function() { + //console.log("[ChaZD] Success update settings toggleKey = " + this.value); + }); +}; // showDuration.addEventListener("onclick", function (event) { // currentDuration.innerHTML = event.target.value; // updateSetting("duration", event.target.value); diff --git a/src/javascript/selection.js b/src/javascript/selection.js index 775f67d..c23d877 100644 --- a/src/javascript/selection.js +++ b/src/javascript/selection.js @@ -8,45 +8,6 @@ }; var timeout; - var currentSettings = {}; - chrome.storage.sync.get(null, function(items) { - for (var key in items) { - currentSettings[key] = items[key]; - } - }); - - chrome.storage.onChanged.addListener(function(changes) { - // for (var key in changes) { - // console.log("[ChaZD]Settings Update, [%s] %s => %s", key, changes[key].oldValue, changes[key].newValue); - // } - if (changes.linkQuery !== undefined) { - currentSettings.linkQuery = changes.linkQuery.newValue; - } - if (changes.useHttps !== undefined) { - currentSettings.useHttps = changes.useHttps.newValue; - } - if (changes.autoAudio !== undefined) { - currentSettings.autoAudio = changes.autoAudio.newValue; - } - if (changes.defaultVoice !== undefined) { - currentSettings.defaultVoice = changes.defaultVoice.newValue; - } - if (changes.selectMode !== undefined) { - currentSettings.selectMode = changes.selectMode.newValue; - } - if (changes.toggleKey !== undefined) { - currentSettings.toggleKey = changes.toggleKey.newValue; - } - if (changes.autoHide !== undefined) { - currentSettings.autoHide = changes.autoHide.newValue; - } - if (changes.showDuration !== undefined) { - currentSettings.showDuration = changes.showDuration.newValue; - } - if (changes.showPosition !== undefined) { - currentSettings.showPosition = changes.showPosition.newValue; - } - }); var queryInPage = function(event) { var selection = window.getSelection && window.getSelection(); @@ -224,21 +185,32 @@ $resultContainer.appendChild($searchingNode); chrome.runtime.sendMessage({ queryWord: text, - source: "select", - useHttps: useHttps + source: "select" }, function(response) { var resultObj = response; $searchingNode.innerHTML = ""; - if (resultObj.validMessage === "query success") { - + if (resultObj.Code === 0) { $resultContainer.innerHTML = resultObj.titleBlock; - var singleVoiceButton = $resultContainer.querySelector(".voice-container"); + var buildVoice = function (voice) { + var src = voice.getAttribute("data-src"); + var audioBlock = document.createElement("audio"); + if(currentSettings.defaultVoice){ + src += "&type=" + currentSettings.defaultVoice; + } + audioBlock.setAttribute("src", src); + voice.appendChild(audioBlock); + if (currentSettings.autoAudio === true) { + audioBlock.play(); + } + audioBlock.addEventListener("ended", function (event) { + this.load(); + }); + voice.addEventListener("click", function (event) { + audioBlock.play(); + }); + }; buildVoice(singleVoiceButton); - - //console.log("inner onclick:" + singleVoiceButton.onclick); - //console.log(document.querySelector(".voice-container") === singleVoiceButton); - var temp = document.createElement("div"); if (resultObj.basicBlock) { temp.innerHTML = resultObj.basicBlock; @@ -254,39 +226,18 @@ $resultContainer.innerHTML = "╮(╯▽╰)╭划词君无能为力啊
    还是右键问问谷歌君吧=>"; } } else { - if (resultObj.errorCode == 20) { + if (resultObj.Code == 20) { $resultContainer.innerHTML = "

    这段文字太长,词典君无能为力了(┬_┬)

    试试短一点的吧~

    "; - } else if (resultObj.errorCode == 40) { + } else if (resultObj.Code == 40) { $resultContainer.innerHTML = "

    对不起,这段文字太高深了,请饶过词典君吧(┬_┬)

    "; } else { $resultContainer.innerHTML = "

    词典君罢工啦(┬_┬)

    是不是网络不太好?

    稍后再试一次吧

    "; - } + } } }); - return $resultContainer; }; - function buildVoice(voice) { - var src = voice.getAttribute("data-src"); - //console.log("voice src: [] " + src); - var audioBlock = document.createElement("audio"); - audioBlock.setAttribute("src", src + "&type=" + currentSettings.defaultVoice); - //audioBlock.setAttribute("ended", "this.load()"); - voice.appendChild(audioBlock); - if (currentSettings.autoAudio === true) { - audioBlock.play(); - } - audioBlock.addEventListener("ended", function (event) { - //console.log("loading src: " + this.getAttribute("src")); - this.load(); - }); - voice.addEventListener("click", function (event) { - //console.log("playing src: " + audioBlock.getAttribute("src")); - audioBlock.play(); - }); - } - function isExist(newRange, oldRange) { if (newRange.top === oldRange.top && newRange.bottom === oldRange.bottom && diff --git a/src/javascript/utility.js b/src/javascript/utility.js index 0177041..2e38b42 100644 --- a/src/javascript/utility.js +++ b/src/javascript/utility.js @@ -1,14 +1,17 @@ -var api = { - key: 1116151381, - keyfrom : "youdaocidian" -}; - -var urls = { - dict : "http://fanyi.youdao.com/openapi.do?keyfrom=" + api.keyfrom +"&key="+ api.key +"&type=data&doctype=json&version=1.1&q=", - voice : "http://dict.youdao.com/dictvoice?audio=", - dictHttps : "https://fanyi.youdao.com/openapi.do?keyfrom=" + api.keyfrom +"&key="+ api.key +"&type=data&doctype=json&version=1.1&q=", - voiceHttps : "https://dict.youdao.com/dictvoice?audio=", -}; +function ajax(method,url,data,cb,before){ + var xhr = new XMLHttpRequest(); + xhr.open(method, url, true); + xhr.onreadystatechange = function(){ + if (xhr.readyState != 4) { + return; + } + cb(xhr); + }; + if(before !== undefined) { + before(xhr); + } + xhr.send(data); +} var settings = { selectMode : "mouseSelect", //划词的形式:直接划词 or Ctrl + 划词 @@ -20,16 +23,58 @@ var settings = { autoAudio: false, //划词自动发音 autoHide: false, //自动隐藏翻译结果 showDuration: 3, //翻译结果显示持续时间 - defaultVoice: 1, //划词默认发音:1--英音;2--美音 + defaultVoice: 0, //划词默认发音:0--真人发音;1--英音;2--美音 useHttps: false, //是否使用 HTTPS 的接口 + autoLearn:true, //是否自动加入生词本 + apiName:"shanbay" }; - +var currentSettings = settings; +chrome.storage.sync.get(null, function(items) { + for (var key in items) { + currentSettings[key] = items[key]; + } +}); +chrome.storage.onChanged.addListener(function(changes) { + if (changes.linkQuery !== undefined) { + currentSettings.linkQuery = changes.linkQuery.newValue; + } + if (changes.useHttps !== undefined) { + currentSettings.useHttps = changes.useHttps.newValue; + } + if (changes.autoAudio !== undefined) { + currentSettings.autoAudio = changes.autoAudio.newValue; + } + if (changes.defaultVoice !== undefined) { + currentSettings.defaultVoice = changes.defaultVoice.newValue; + } + if (changes.selectMode !== undefined) { + currentSettings.selectMode = changes.selectMode.newValue; + } + if (changes.toggleKey !== undefined) { + currentSettings.toggleKey = changes.toggleKey.newValue; + } + if (changes.autoHide !== undefined) { + currentSettings.autoHide = changes.autoHide.newValue; + } + if (changes.showDuration !== undefined) { + currentSettings.showDuration = changes.showDuration.newValue; + } + if (changes.showPosition !== undefined) { + currentSettings.showPosition = changes.showPosition.newValue; + } + if (changes.autoLearn !== undefined) { + currentSettings.autoLearn = changes.autoLearn.newValue; + } + if (changes.apiName !== undefined) { + currentSettings.apiName = changes.apiName.newValue; + } +}); var frame = { //title frame titleContainer : "
    #{1}#{2}
    ", titleWord : "
    #{1}#{2}
    ", voiceContainer : "
    ", - titleTranslation : "
    #{1}
    ", + titleTranslation : "
    #{1}
    ", //basic frame basicContainer : "
    #{1}#{2}
    ", @@ -50,6 +95,323 @@ var frame = { webExplainsList : "
      #{1}
    ", webExplain : "
  • #{1}#{2}
  • " }; +var youdao = function(){ + var config = {key: 1116151381,keyfrom : "youdaocidian"}; + var urls = { + dict : "http://fanyi.youdao.com/openapi.do?keyfrom=" + config.keyfrom +"&key="+ config.key +"&type=data&doctype=json&version=1.1&q=", + voice : "http://dict.youdao.com/dictvoice?audio=", + dictHttps : "https://fanyi.youdao.com/openapi.do?keyfrom=" + config.keyfrom +"&key="+ config.key +"&type=data&doctype=json&version=1.1&q=", + voiceHttps : "https://dict.youdao.com/dictvoice?audio=" + }; + var self = this; + self.initVoice = function (src, type) { + var title = ""; + if(type === 1){ + title = "英音"; + } else if (type === 2){ + title = "美音"; + } else { + title = "真人发音"; + } + return fmt(frame.voiceContainer, src, title); + }; + self.checkCode = function (Code) { + var response = { + "message": "", + "error": 0, + "Code": 0 + }; + switch (Code) { + case 0: + response.Message = "查询成功"; + break; + case 20: + response.Message = "要翻译的文本过长"; + response.error = 1; + response.Code = 20; + break; + case 30: + response.Message = "无法进行有效的翻译"; + response.error = 1; + response.Code = 30; + break; + case 40: + response.Message = "不支持的语言类型"; + response.error = 1; + response.Code = 40; + break; + case 50: + response.Message = "无效的key"; + response.error = 1; + response.Code = 50; + break; + case 60: + response.Message = "无辞典结果"; + response.error = 1; + response.Code = 60; + break; + default: + } + return response; + }; + self.shortWord = function (longWord) { + return longWord.slice(0, longWord.lastIndexOf(" ", 50)).concat(" ..."); + }; + self.getVoice = function(result, type){ + var src = (currentSettings.useHttps ? urls.voiceHttps : urls.voice) + result.query; + if(type !== undefined) { + src = src + "&type=" + type; + } + return src; + }; + self.initTitle = function (result) { + var translation = result.translation; + var queryWord = result.query; + var voiceContainer = self.initVoice(self.getVoice(result)); + queryWord = queryWord.length >= 50 && self.wordSource == "select" ? self.shortWord(queryWord) : queryWord; + var titleWord = fmt(frame.titleWord, queryWord, voiceContainer); + var titleTranslation = translation?fmt(frame.titleTranslation, translation.toString()): ""; + return { + titleBlock : fmt(frame.titleContainer, titleWord, titleTranslation, queryWord.length >=50 ? "long-text" : "") + }; + }; + self.haveTranslation = function (result) { + if (self.checkCode(result.errorCode).error||!translation) { + return false; + } + var translation = result.translation; + var queryWord = result.query; + if (trim(queryWord.toLowerCase()) === trim(translation.toString().toLowerCase())) { + return false; + } + return true; + }; + self.parseBasicPhonetic = function (result) { + var basic = result.basic; + var ukPhonetic = basic["uk-phonetic"]; + var usPhonetic = basic["us-phonetic"]; + if (ukPhonetic !== undefined && usPhonetic !== undefined) { + var ukVoice = self.initVoice(self.getVoice(result,1), 1); + var ukPhoneticContainer = fmt(frame.ukPhoneticContainer, "[" + ukPhonetic + "]" + ukVoice); + var usVoice = self.initVoice(self.getVoice(result,2), 2); + var usPhoneticContainer = fmt(frame.usPhoneticContainer, "[" + usPhonetic + "]" + usVoice); + return fmt(frame.phoneticContainer, ukPhoneticContainer, usPhoneticContainer); + } + return fmt(frame.phoneticContainer, "", ""); + }; + self.parseProperty = function (property) { + var propertyText = ""; + switch (property) { + case "adj." : + propertyText = "形容词"; + break; + case "adv." : + propertyText = "副词"; + break; + case "n." : + propertyText = "名词"; + break; + case "vi." : + propertyText = "不及物动词"; + break; + case "vt." : + propertyText = "及物动词"; + break; + case "prep." : + propertyText = "介词"; + break; + case "conj." : + propertyText = "连词"; + break; + case "int." : + propertyText = "感叹词"; + break; + case "abbr." : + propertyText = "代词"; + break; + case "pron." : + propertyText = ""; + break; + default : + } + return propertyText; + }; + self.parseBasicExplains = function (result) { + var basic = result.basic; + var explains = basic.explains; + var i; + var explainsContent = ""; + for (i = 0; i < explains.length; i++) { + var currentExplain = explains[i]; + var haveProperty = currentExplain.indexOf(". "); + var property = (haveProperty !== -1) ? currentExplain.slice(0, haveProperty + 1) : ""; + var propertyTitle = self.parseProperty(property); + var propertyContainer = fmt(frame.propertyContainer, propertyTitle, property); + var explainText = (haveProperty !== -1) ? currentExplain.slice(haveProperty + 1) : currentExplain; + var explain = fmt(frame.explain, propertyContainer, explainText); + explainsContent += explain; + } + return fmt(frame.explainsContainer, fmt(frame.explainsList, explainsContent)); + }; + self.parseBasicResult = function (result) { + var phoneticBlock = self.parseBasicPhonetic(result); + var explainsBlock = self.parseBasicExplains(result); + var basicContainer = fmt(frame.basicContainer, phoneticBlock, explainsBlock); + return basicContainer; + }; + self.parseWebResult = function (result) { + var web = result.web; + var webExplainsContent = ""; + var i; + for (i = 0; i < web.length ; i++) { + var webExplain = fmt(frame.webExplain, web[i].key, web[i].value); + webExplainsContent += webExplain; + } + return fmt(frame.webExplainsContainer, fmt(frame.webExplainsList, webExplainsContent)); + }; + self.parseResult = function (result) { + //console.log("Response Text: \n" + responseText); + var resultObj = self.checkCode(result.errorCode); + resultObj.haveWebTranslation = false; + if (!resultObj.error) { + var title = self.initTitle(result); + resultObj.titleBlock = title.titleBlock; + resultObj.haveTranslation = self.haveTranslation(result); + if (result.basic !== undefined) { + var basicBlock = self.parseBasicResult(result); + resultObj.basicBlock = basicBlock; + } + if (result.web !== undefined) { + var webBlock = self.parseWebResult(result); + resultObj.haveWebTranslation = true; + resultObj.webBlock = webBlock; + } + } + return resultObj; + }; + var Query = function(queryWord, wordSource, sendResponse) { + self.wordSource = wordSource; + var url = (currentSettings.useHttps ? urls.dictHttps : urls.dict) + queryWord; + ajax("GET", url, null, function (xhr) { + var result = JSON.parse(xhr.responseText); + if (queryWord.indexOf("-") != -1 && !self.checkCode(result.errorCode).error && !self.haveTranslation(result)) { + //优化使用连字符的词的查询结果 + new Query(queryWord.replace(/-/g, " "), wordSource, sendResponse); + } else { + var ret = self.parseResult(result); + sendResponse(ret); + } + }); + }; + self.Query = Query; +}; + +var shanbay = function(){ + var self = this; + self.dict = "http://www.shanbay.com/api/v1/bdc/search/?word="; + self.learn = "http://www.shanbay.com/api/v1/bdc/learning/"; + self.login = "http://www.shanbay.com/accounts/login/"; + youdao.call(this); + + /*jshint camelcase: false */ + self.getVoice = function(result,type){ + var basic = result.basic; + var src = basic.audio; + if(type == 1) { + src = basic.uk_audio; + }else if(type == 2){ + src = basic.us_audio; + } + return src; + }; + self.parseBasicPhonetic = function (result) { + var basic = result.basic; + if (basic.pronunciations) { + var ukPhonetic = basic.pronunciations.uk; + var usPhonetic = basic.pronunciations.us; + if(ukPhonetic !== undefined && usPhonetic !== undefined){ + var ukVoice = self.initVoice(self.getVoice(result,1), 1); + var ukPhoneticContainer = fmt(frame.ukPhoneticContainer, "[" + ukPhonetic + "]" + ukVoice); + var usVoice = self.initVoice(self.getVoice(result,2), 2); + var usPhoneticContainer = fmt(frame.usPhoneticContainer, "[" + usPhonetic + "]" + usVoice); + return fmt(frame.phoneticContainer, ukPhoneticContainer, usPhoneticContainer); + } + } + var voice = self.initVoice(self.getVoice(result)); + var phoneticContainer = fmt(frame.usPhoneticContainer, "[" + basic.phonetic + "]" + voice); + return fmt(frame.phoneticContainer, phoneticContainer, ""); + }; + self.parseBasicExplains = function (result) { + var basic = result.basic; + var definition = basic.definition; + var i; + var explainsContent = ""; + var explains = definition.split("\n"); + for (i = 0; i < explains.length; i++) { + var currentExplain = explains[i]; + var haveProperty = currentExplain.indexOf("."); + var property = (haveProperty !== -1) ? currentExplain.slice(0, haveProperty + 1) : ""; + var propertyTitle = self.parseProperty(property); + var propertyContainer = fmt(frame.propertyContainer, propertyTitle, property); + var explainText = (haveProperty !== -1) ? currentExplain.slice(haveProperty + 1) : currentExplain; + var explain = fmt(frame.explain, propertyContainer, explainText); + explainsContent += explain; + } + return fmt(frame.explainsContainer, fmt(frame.explainsList, explainsContent)); + }; + self.Query = function(queryWord, wordSource, sendResponse) { + var url = self.dict + queryWord; + /*jshint camelcase: false */ + ajax("GET", url, null, function (xhr) { + var result = JSON.parse(xhr.responseText); + var data = result.data; + if (result.status_code === 0) { + data = {basic:{ + pronunciations:data.pronunciations, + phonetic:data.pron, + audio:data.audio, + us_audio:data.us_audio, + uk_audio:data.uk_audio, + cn_definition:data.cn_definition, + en_definition:data.en_definition, + definition:data.definition + },query:data.content,errorCode:0}; + var ret = self.parseResult(data); + sendResponse(ret); + data = {id: result.data.id, content_type: "vocabulary"}; + //加入生词本 + if(currentSettings.autoLearn){ + ajax("POST", self.learn, JSON.stringify(data), function (xhr) { + var result = JSON.parse(xhr.responseText); + if(xhr.status == 401){ + if (confirm(result.msg+"\n你选择了自动加入生词本,但你没有登陆扇贝网或登陆已失效,是否现在登陆?")){ + chrome.tabs.create({ url: self.login }); + }else{ + currentSettings.autoLearn = false; + } + } + }, function (xhr) { + xhr.setRequestHeader("Content-Type", "application/json"); + }); + } + } else if (result.status_code === 1) { + var y = new youdao(); + y.Query(queryWord, wordSource, sendResponse); + } + }); + }; +}; + +var xyuu = function(){ + shanbay.call(this); + this.dict ="http://dict.xyuu.com.cn/search/?word="; +}; + +var api = { + youdao:youdao, + shanbay:shanbay, + xyuu:xyuu +}; //判断一个初始化后的对象是否为空 function isEmpty(obj) {