Google Translate Tooltip

Translates selected text into a tooltip.

Este script não deve ser instalado diretamente. Este script é uma biblioteca de outros scripts para incluir com o diretório meta // @require https://update.greasyfork.org/scripts/3529/10683/Google%20Translate%20Tooltip.js

// ==UserScript==
// @name        Google Translate Tooltip
// @namespace   steely.wing
// @version     1.9
// @description Translates selected text into a tooltip.
// @license     GPL version 3 or any later version; http://www.gnu.org/copyleft/gpl.html
// @copyright   2014, Wing Leong (http://steelywing.iblogger.org/)
// @include     *
// @require     http://code.jquery.com/jquery-2.1.0.min.js
// @grant       GM_getValue
// @grant       GM_setValue
// @grant       GM_xmlhttpRequest 
// ==/UserScript==
function log(){}function getSelection(){var t=window.getSelection().toString(),e=$(":focus").filter(":text, textarea");return!t&&e.length&&(t=e.val().slice(e[0].selectionStart,e[0].selectionEnd)),t}function tts(t,e,n,i,o){t instanceof AudioContext&&"string"==typeof e&&"string"==typeof n&&"function"==typeof i&&("undefined"==typeof o&&(o=3),GM_xmlhttpRequest({method:"GET",overrideMimeType:"text/plain; charset=x-user-defined",url:"https://translate.google.cn/translate_tts?"+$.param({client:"t",tl:e,ie:"UTF-8",q:n}),onload:function(a){var s=a.responseText.length,r=new Uint8Array(s);if(log("TTS length",s),0==s)return void(+o>0&&tts(t,e,n,i,o-1));for(var l=0;s>l;l++)r[l]=a.responseText.charCodeAt(l);t.decodeAudioData(r.buffer,function(t){log("TTS buffer decode success"),i(t)})}}))}function translate(t,e,n){"string"==typeof t&&(t=t.trim().replace(/[\u0000-\u001f]/g,""),t&&(log("Translating",t),e&&$tooltip.css("left",e),n&&$tooltip.css("top",n),audioBuffer=null,$ttsButton.toggle(!1),$tooltip.display(!0).width("auto").find(".translation").text("Loading...").end(),GM_xmlhttpRequest({method:"GET",url:"https://translate.google.cn/translate_a/t?"+$.param({client:"dict-chrome-ex",sl:GM_getValue("sl")||"auto",tl:GM_getValue("tl")||"auto",q:t}),onload:function(e){var n,i=[];try{n=JSON.parse(e.responseText)}catch(o){return log(o,e),void $tooltip.find(".translation").text("Parsing JSON error").end().width("auto")}return log("Translated JSON",n),$.each(n.sentences,function(t,e){e.trans&&i.push($("<div>").text(e.trans))}),0===i.length?void $tooltip.display(!1):($tooltip.find(".translation").empty().append(i).end().width("auto"),void tts(audioContext,n.src,t,function(t){audioBuffer=t,$ttsButton.toggle(!0)}))}})))}const TTS_ICON="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAmtJREFUeNrsVz2P2kAQ5ZIraHGHriPdKR10aUkTcSV0afkLlGlxRwtdqpOgIw0SdFQnmT9wErRXRIL8AKTNvtU8a7zYhyz27hpGGmy863lv52vXN8aYylU+Uj4Htle3+sNq1erLey/mq9W/Vo3ok9XOWwCNrCZyvVcrd+Ddbtc0m02jiDyGAr6TVWnjRyHRIzhlOByaWq3GeQt5/3JwrC5JEtPv92m8L652gNPpNCWBeY1Gg/PmQcD3+326QjEce15JSUIwX3liFAQ8jwD+L5dLFwYSGY/HqScUwcLEvBd3xkpzwT0CK1wBTgEwQ0JPqPnzohI6+q4sAvcMPnPuYDA4CVG73c4LxTefwBoDSCy8qDUP3CPgQGicgBDc4xkTEwTlnV8aPKK7yggJsPRAlPWPMQiAuTAIwqTCFoYA3mP8t9ute4bSo2CctkFSCByCEaCSBKuAyccwMJQqD4Bb+RSgQ/7Bz263yx20gJXXxkMQeACIXan7czhkvOuAMW7zo9DARSFAvOleJhmSUcec/5kj4KU9sLf6D8x99mVkNptVer2eu7fl5q6TycRd6Z3NZsPp6c2t6gMPrVbrxFUw9pr74OIoijLzbSK6xcRxnCGwWq103znp+Yu8TqjbaUEVzOlm3Y5ZDewByv1HdY44kS+yt1Mfi0goAokuO8Sd4LqNq+37d9nw5pJQBEbsiGi1rHMNzs3p3OpLkfC2Y30WzGxKChz685J6T0kAXJ10OhI69wyx9rflEOAZEkoX8vy73gn9g0kocEpH3K5PNlWeC1SvNxK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data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAnFJREFUeNrUVz1LI0EYnvXyA4zXC8ZKEZuEa7wy+QNCghZnmXS28Sdkr/LKpLvqjgSuOBCEpBC0UTZwlY0kVtdu/sDJ+DzLTNhbd2Z3s9HgCw87mZnM+/3OO46UUqySCnkPcBwn1//XxIqp8Ipnb1jW/PmIMZAHMXQKXPNoC7i+F7gwKQjh4118PgPbKbT+C3zjoFgsGjfNZjN+HoD9JO3OgX8J2rxAv9+XNqpWq3pvrWDR/Ac+Rxw3m01RKpUS1Z9Op6LX6wnXdQWYGK0Qmi+aNKcfJTZKz/NkWuJebYVyuSx934/dV6/X9b6GSYDfYVO2220JCwQC2RB1RafTWVgARkmgwXA4zOJ/T48ptInCAqzF+J75u04/EePxWC99BT5awEwpcyOYC2g/P3MwGOjIz1cJIbwfhSoqO8BNHHMGZaPRELVaLV6IGPNv6AAk0Y/KXK7BXQcms3e73f9cxMBkoDKe1Nx2LgEyMP8C3Ebi5TKXBTIwv1Z7dWHz1HdxF4B2dYW0MY+k5oEpsBYRoMk5VEgrc11D1NzZMvuBIDeZojqyGe2tVstedpclABSjAHcUgOnF2h9ifvJWDckh8AtCfAoVKzK/WKoAIRNuokq6keUrBU17utGw9QNWAVjdwOgRvt3i9aqvVfw+yqIZ6v38ilY0ib324zoiCPCd5mQfgMgODhmNRsZ6HiVUvEBwuqZSqXDqKeh+hLhPTMNonjPVJpOJzEK8RXmVh+rAubHxMfWEsAJ9+Qf4kMWnoZ5P00/g2JZStp6QlqA7phn7wplqak4THzZpn2aqT0hLfuqXVd634bt/mjmrfh2v3ALPAgwAAuGRJ1wDDiMAAAAASUVORK5CYII=",LANGUAGES={auto:"Detect language",af:"Afrikaans",sq:"Albanian",ar:"Arabic",hy:"Armenian",az:"Aerbaijani",eu:"Basque",be:"Belarusian",bn:"Bengali",bg:"Bulgarian",ca:"Catalan","zh-CN":"Chinese (simplified)","zh-TW":"Chinese (traditional)",hr:"Croatian",cs:"Czech",da:"Danish",nl:"Dutch",en:"English",et:"Estonian",tl:"Filipino",fi:"Finnish",fr:"French",gl:"Galician",ka:"Georgian",de:"German",el:"Greek",ht:"Haitian Creole",iw:"Hebrew",hi:"Hindi",hu:"Hungarian",is:"Icelandic",id:"Indonesian",ga:"Irish",it:"Italian",ja:"Japanese",ko:"Korean",lv:"Latvian",lt:"Lithuanian",mk:"Macedonian",ms:"Malay",mt:"Maltese",no:"Norwegian",fa:"Persian",pl:"Polish",pt:"Portuguese",ro:"Romanian",ru:"Russian",sr:"Serbian",sk:"Slovak",sl:"Slovenian",es:"Spanish",sw:"Swahili",sv:"Swedish",th:"Thai",tr:"Turkish",uk:"Ukrainian",ur:"Urdu",vi:"Vietnamese",cy:"Welsh",yi:"Yiddish"},STYLE="    <style>        .gtt,        .gtt *,        .gtt.setting,        .gtt.setting * {            -moz-box-sizing: content-box !important;            box-sizing: content-box !important;            padding: 0 !important;            margin: 0 !important;        }                .gtt, .gtt.setting {            position: absolute !important;            display: block;            padding: .5em 1em !important;            margin: 0 !important;            font-family: sans-serif !important;            font-size: 14px !important;            line-height: 1.2em !important;            min-height: 1.2em !important;            max-width: 400px !important;            color: #fff !important;            z-index: 100000 !important;            background-color: #333 !important;            border-radius: 4px !important;            overflow: hidden !important;            -webkit-transition: width .2s;            transition: width .2s;        }                .gtt * {            background: none !important;            white-space: nowrap !important;            box-shadow: none !important;            border-width: 0 !important;        }                .gtt .toolbar {            position: absolute !important;            right: .5em !important;            white-space: nowrap !important;        }                .gtt .toolbar .button {            position: relative !important;            width: 1.2em !important;            height: 1.2em !important;            float: none !important;            vertical-align: baseline !important;            cursor: pointer;        }                .gtt .translation * {            color: #fff !important;            text-align: left !important;            white-space: normal !important;        }                .gtt select {            background-color: #fff !important;            color: #000 !important;        }                .gtt.setting div {            text-align: left !important;            padding: .5em !important;        }                .gtt .close.button {            float: right !important;            padding: 0 !important;            opacity: 1;            cursor: pointer;            color: #fff !important;        }    </style>",TOOLTIP='    <div class="gtt">        <div class="toolbar">            <img class="tts button" src="'+TTS_ICON+'">            <img class="link button" src="'+LINK_ICON+'">            <img class="setting button" src="'+SETTING_ICON+'">        </div>        <div class="translation"></div>    </div>',SETTING='    <div class="gtt setting">        <div class="close button">?</div>        <div>            Trigger key:            <label>                <input name="ctrl" type="checkbox"> Ctrl            </label>        </div>        <div>            <select name="sl"></select>            →            <select name="tl"></select>        </div>    </div>';!function(t){t.fn.draggable=function(e){var n=this,i=this;return e=t.extend({},{handle:null,handleChildren:!0,cursor:"move"},e),e.handle&&(n=t(e.handle)),n.css({"-webkit-user-select":"none","-moz-user-select":"none","-ms-user-select":"none","user-select":"none",cursor:e.cursor}).on("mousedown",function(n){var o=i.offset().left-n.pageX,a=i.offset().top-n.pageY,s=i.css("z-index");(e.handleChildren||n.target==this)&&(i.css("z-index",1e5),t(document.documentElement).on("mousemove.draggable",function(t){i.offset({left:o+t.pageX,top:a+t.pageY})}).one("mouseup",function(){t(this).off("mousemove.draggable"),i.css("z-index",s)}))}),this}}(jQuery),function(t){var e=t.fn.toggle;t.fn.toggle=function(t){if("undefined"==typeof t&&(t=!this.data("visible")),t===!0)this.stop().fadeIn("fast");else{if(t!==!1)return e.apply(this,arguments);this.stop().fadeOut("fast")}return this.data("visible",t),this.trigger("toggle"),this},t.fn.display=function(e){return"undefined"==typeof e&&(e=!this.data("visible")),e?(t(document.body).append(this),this.stop().fadeIn("fast")):this.stop().fadeOut("fast",function(){t(this).detach()}),this.data("visible",e),this.trigger("display"),this}}(jQuery);var selectedText,audioContext,audioBuffer,$tooltip=$(TOOLTIP).hide(),$setting=$(SETTING).hide(),$toolbar=$tooltip.find(".toolbar").hide(),$settingButton=$toolbar.find(".setting.button"),$linkButton=$toolbar.find(".link.button"),$ttsButton=$toolbar.find(".tts.button");$toolbar.find(".button").addBack().on("toggle",function(){$tooltip.trigger("width")}),$tooltip.on("width",function(){var t=$tooltip.width(),e=$tooltip.width("auto").width()+1;$toolbar.data("visible")&&(e+=$settingButton.width()+$linkButton.width()+8,audioBuffer&&(e+=$ttsButton.width())),$tooltip.width(t).width(e)}).mouseenter(function(){$toolbar.toggle(!0)}).mouseleave(function(){$toolbar.toggle(!1)}).draggable({handle:$tooltip.find(".translation")}),$settingButton.click(function(){var t=$tooltip.offset();$setting.display().offset({left:t.left,top:t.top+$tooltip.outerHeight()+4})}),$linkButton.click(function(){window.open("https://translate.google.cn/#"+encodeURIComponent(GM_getValue("sl")||"auto")+"/"+encodeURIComponent(GM_getValue("tl")||"auto")+"/"+encodeURIComponent(selectedText),"_blank")}),$setting.draggable({}).find(".close.button").click(function(t){$setting.display(!1),t.preventDefault()}).end(),$.each(LANGUAGES,function(t,e){$setting.find("select").each(function(){$(this).append($("<option>").attr("value",t).text(e))})}),$(document.head).append(STYLE);try{window.AudioContext=window.AudioContext||window.webkitAudioContext,audioContext=new AudioContext,$ttsButton.click(function(){var t;return audioBuffer?(t=audioContext.createBufferSource(),t.buffer=audioBuffer,t.connect(audioContext.destination),t.start(0),void log("Playing TTS",audioBuffer)):void log("No TTS buffer")})}catch(e){log("Web Audio API is not supported in this browser",e)}$setting.find("select").change(function(){GM_setValue($(this).attr("name"),$(this).find(":selected").val()),translate(selectedText)}).each(function(){var t=GM_getValue($(this).attr("name"))||"auto";$(this).val(t)}).end().find('[name="ctrl"]').prop("checked",Boolean(GM_getValue("ctrl"))).change(function(){GM_setValue("ctrl",$(this).prop("checked"))}).end(),document.addEventListener("mousedown",function(t){t.target==$setting[0]||$setting.has(t.target).length||t.target==$tooltip[0]||$tooltip.has(t.target).length||($tooltip.display(!1),$setting.display(!1))},!0),document.addEventListener("mouseup",function(t){t.target==$tooltip[0]||$tooltip.has(t.target).length||t.target==$setting[0]||$setting.has(t.target).length||GM_getValue("ctrl")&&!t.ctrlKey||(selectedText=getSelection(),translate(selectedText,t.pageX+8,t.pageY+8))},!0);