-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgTranslator.uc.js
418 lines (387 loc) · 15.3 KB
/
gTranslator.uc.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
// ==UserScript==
// @name gTranslator.uc.js
// @description google_translator扩展的UC脚本版
// @author Dannylee
// @namespace [email protected]
// @include main
// @license MIT License
// @compatibility Firefox 4
// @charset UTF-8
// @version 基于 Dannylee 脚本uc_google_translator.uc.js v2.3.2.2
// @note 左键点击按钮直接翻译,如果有选中文字就翻译文字,否则翻译网页
// @note 右键弹出设置菜单
// @note 不勾选弹窗显示则直接替换原文本,否则弹窗显示翻译结果
// @note 不勾选对比显示则只显示翻译结果,否则对比显示翻译结果
// ==/UserScript==
var gTranslator = {
_prefs : null,
_targetlang : "zh-CN",
_showpopuptext : true,
_showoritext : false,
_timer : null,
onLoad : function () {
this._prefs = Components.classes["@mozilla.org/preferences-service;1"]
.getService(Components.interfaces.nsIPrefService)
.getBranch("uc.gTranslator.");
this._prefs.QueryInterface(Components.interfaces.nsIPrefBranch2);
if (!this._prefs.prefHasUserValue("targetlang")) {
this._prefs.setCharPref("targetlang", this._targetlang);
} else {
this._targetlang = this._prefs.getCharPref("targetlang");
}
if (!this._prefs.prefHasUserValue("showpopuptext")) {
this._prefs.setBoolPref("showpopuptext", this._showpopuptext);
} else {
this._showpopuptext = this._prefs.getBoolPref("showpopuptext");
}
if (!this._prefs.prefHasUserValue("showoritext")) {
this._prefs.setBoolPref("showoritext", this._showoritext);
} else {
this._showoritext = this._prefs.getBoolPref("showoritext");
}
var overlay = '\
<overlay xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul" \
xmlns:html="http://www.w3.org/1999/xhtml"> \
<toolbarpalette id="urlbar-icons">\
<toolbarbutton id="gTranslator" label="翻译器" \
context="gTranslator-contextmenu"\
tooltiptext = "左键翻译|右键菜单" \
onclick="if(event.button === 0) gTranslator.ToolBarTranslatorClick(event);" >\
<menupopup id="gTranslator-contextmenu" \
onpopupshowing="gTranslator.showStatbarContextMenu(event);">\
<menuitem id="translateselected-gTranslator" \
label="翻译选定文本" \
onclick="gTranslator.selectionTranslation(event);"/> \
<menuitem id="translatepage-gTranslator" \
label="翻译整个页面" \
onclick="gTranslator.pageTranslation(event);"/> \
<menuseparator/> \
<menuitem label="翻译为简中" \
id="trtid1" \
type="checkbox" \
value="zh-CN" \
onclick = "gTranslator.settargetlang(event);" /> \
<menuitem label="翻译为英文" \
id="trtid2" \
type="checkbox" \
value="en" \
onclick = "gTranslator.settargetlang(event);" /> \
<menuitem label="翻译为德文" \
id="trtid3" \
type="checkbox" \
value="de" \
onclick = "gTranslator.settargetlang(event);" /> \
<menuseparator/> \
<menuitem id="showsreplaced" \
label="弹窗显示翻译结果" \
tooltiptext = "选中弹窗翻译,否则替换原文" \
type="checkbox" \
value="' + this._showpopuptext + '" \
onclick = "gTranslator.setshowmode(event);"/> \
<menuitem id="showoritext" \
label="对比显示翻译结果" \
tooltiptext = "选中同时显示译文和原文,否则只显示译文" \
value="' + this._showoritext + '" \
type="checkbox" \
onclick = "gTranslator.setoridisplay(event);"/> \
</menupopup>\
</toolbarbutton>\
</toolbarpalette>\
</overlay>';
overlay = "data:application/vnd.mozilla.xul+xml;charset=utf-8," + encodeURI(overlay);
window.userChrome_js.loadOverlay(overlay, gTranslator);
var css = '\
#gTranslator {\
list-style-image: url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAA4AAAAOBAMAAADtZjDiAAAAMFBMVEUAAABOSkqmpKRaV1dBPT2amJjMy8uAfn7m5eV0cXGNi4vZ2Njy8vKzsbFnZGTAvr7viNsdAAAAAXRSTlMAQObYZgAAAF5JREFUCNdjAIMLQBzEplosD6RVokQDFYA0l85jS5AcLwOzE5BKF9EwnDiDgYFJZaGSmIk9A8MW1WJBGwYgvV1VIBdEP5woKH6AgSHlkZIASF9yAxOIBpkEpTkCGBgA4S0RikQ4FIAAAAAASUVORK5CYII=");\
-moz-appearance: none !important;\
box-shadow: none !important;\
border: none !important;\
min-width: 18px !important;\
min-height: 18px !important;\
margin-right: -5px !important;\
-moz-box-align: center !important;\
-moz-box-pack: center !important;\
}\
'.replace(/[\r\n\t]/g, '');
function addStyle(css) {
var pi = document.createProcessingInstruction(
'xml-stylesheet',
'type="text/css" href="data:text/css;utf-8,' + encodeURIComponent(css) + '"');
return document.insertBefore(pi, document.documentElement);
}
gTranslator.style = addStyle(css);
var xmltt = '\
<tooltip id="translationResult" style="-moz-appearance: none;display:-moz-popup;font:message-box;background-color:InfoBackground;color:InfoText;border: 1px solid InfoText;width:450px;">\
<vbox id="translationResultPopupBox">\
<label id="translationResultPopupLabel" flex="1" onclick="gTranslator.copyToClipboard(event,this.textContent);" tooltiptext="左键复制到剪切板、右键关闭!"/>\
</vbox>\
</tooltip>\
';
var rangett = document.createRange();
rangett.selectNodeContents(document.getElementById('mainPopupSet'));
rangett.collapse(false);
rangett.insertNode(rangett.createContextualFragment(xmltt.replace(/\n|\r/g, ''))); //.replace(/\n/g, '')
rangett.detach();
},
observe : function (aSubject, aTopic, aData) {
if (aTopic == "xul-overlay-merged") {
// Application.console.log("GoogleTranslator界面加载完毕!");
document.getElementById("contentAreaContextMenu").addEventListener("popupshowing", this.showContextMenu, false);
window.addEventListener("unload", this, false);
}
},
uninit : function () {
if (this._timer)
clearTimeout(this._timer);
var i = document.getElementById("gTranslator");
if (i)
i.parentNode.removeChild(i);
var i = document.getElementById("gTranslator-contextmenu");
if (i)
i.parentNode.removeChild(i);
document.getElementById("contentAreaContextMenu").removeEventListener("popupshowing", this.showContextMenu, false);
var i = document.getElementById("context-translator");
if (i)
i.parentNode.removeChild(i);
var i = document.getElementById("context-page-translator");
if (i)
i.parentNode.removeChild(i);
var i = document.getElementById("translationResult");
if (i)
i.parentNode.removeChild(i);
window.removeEventListener("unload", this, false);
},
handleEvent : function (event) {
switch (event.type) {
case "unload":
this.uninit();
break;
}
},
settargetlang : function (event) {
if (event.button != 0)
return;
this._targetlang = event.target.value;
this._prefs.setCharPref("targetlang", this._targetlang);
this.settargetlangshow();
},
settargetlangshow : function () {
document.getElementById("trtid1").setAttribute('checked', ((document.getElementById("trtid1").value != this._targetlang) ? false : true));
document.getElementById("trtid2").setAttribute('checked', ((document.getElementById("trtid2").value != this._targetlang) ? false : true));
document.getElementById("trtid3").setAttribute('checked', ((document.getElementById("trtid3").value != this._targetlang) ? false : true));
},
setshowmode : function (event) {
if (event.button != 0)
return;
this._showpopuptext = !this._showpopuptext;
this._prefs.setBoolPref("showpopuptext", this._showpopuptext);
this.showmodeshow();
},
setoridisplay : function (event) {
if (event.button != 0) return;
this._showoritext = !this._showoritext;
this._prefs.setBoolPref("showoritext", this._showoritext);
this.showmodeshow();
},
showmodeshow : function (event) {
document.getElementById("showsreplaced").setAttribute('checked', this._showpopuptext);
document.getElementById("showoritext").setAttribute('checked', this._showoritext);
},
showContextMenu : function () {
document.getElementById("context-translator").hidden = !(gContextMenu.isTextSelected);
document.getElementById("context-page-translator").hidden = (gContextMenu.isTextSelected);
},
showStatbarContextMenu : function () {
if (document.getElementById("translateselected-gTranslator")) {
document.getElementById("translateselected-gTranslator").disabled = !(this.isValidTextLength(this.getSelectedText()));
}
this.settargetlangshow();
this.showmodeshow();
},
getFocusedWindow: function(){
var focusedWindow = document.commandDispatcher.focusedWindow;
if (!focusedWindow || focusedWindow == window)
return window.content;
else
return focusedWindow;
},
getSelectedText: function(e) {
var focusedWindow = this.getFocusedWindow();
var selectedsel = focusedWindow.getSelection();
if (selectedsel && !selectedsel.toString()) {
var node = document.commandDispatcher.focusedElement;
if (node &&
node.ownerDocument.defaultView == focusedWindow &&
(node.type == "text" || node.type == "textarea") &&
'selectionStart' in node &&
node.selectionStart != node.selectionEnd) {
var offsetStart = Math.min(node.selectionStart, node.selectionEnd);
var offsetEnd = Math.max(node.selectionStart, node.selectionEnd);
var selectedText = node.value.substr(offsetStart, offsetEnd-offsetStart);
return selectedText;
}
}
var selectedText = selectedsel ? selectedsel.toString() : "";
return selectedText;
},
isValidTextLength : function (selectedtext) {
if (selectedtext.length > 0 && selectedtext.length <= 38000) {
return true;
} else {
return false;
}
},
ToolBarTranslatorClick : function (e) {
var tbt = document.getElementById("gTranslator");
if (e.target != tbt)
return;
var selectedText = this.getSelectedText();
if (this.isValidTextLength(selectedText)) {
this.selectionTranslation(e);
} else {
this.pageTranslation();
}
},
selectionTranslation : function (event) {
var selectedText = this.getSelectedText();
this.refreshInformation(selectedText);
},
pageTranslation : function (e) {
var cel = this._targetlang;
var docurl = content.location.href;
if (docurl.match(/^about/)) {
return;
} else if(docurl.match(/^https/)) {
docurl = docurl.replace(/https/i, "http");
}
var fordUrl = "http://translate.google.com/translate?hl=" + cel + "&sl=auto&tl=" + cel + "&u=" + encodeURIComponent(docurl);
gBrowser.selectedTab = gBrowser.addTab(fordUrl);
},
refreshInformation : function (whatToTranslate) {
if (this.isValidTextLength(whatToTranslate)) {
var cel = this._targetlang;
var httpRequest = null;
var fullUrl = "http://translate.google.com/translate_t?text="+whatToTranslate+"&hl="+cel+"&langpair=auto|"+cel+"&tbb=1" ;
function removeHTMLTags(mitkell) {
var strTagStrippedText = mitkell.replace(/<br>/ig, "\n").replace(/<\/span>/ig, "");
if (gTranslator._showoritext == false) {
strTagStrippedText = strTagStrippedText.replace(/onmouseout=[^>]+>/ig, "∮")
.replace(/<span title="[^∮]+∮/ig, "")
.replace(/\s*\n+/ig, "\n");
} else {
strTagStrippedText = strTagStrippedText.replace(/<span title=\"/ig, "")
.replace(/\"\sonmouseover[^>]+>/ig, "\n")
.replace(/\s*\n+/ig, "\n");
}
return strTagStrippedText;
}
function infoReceived() {
var output = httpRequest.responseText;
if (whatToTranslate[0] == " ") {
var kezdospace = " ";
} else {
var kezdospace = "";
}
if (whatToTranslate[whatToTranslate.length - 1] == " ") {
var vegespace = " ";
} else {
var vegespace = "";
}
if (output.length) {
output = output.replace(/"/gi, '"');
output = output.replace(/</gi, '<');
output = output.replace(/>/gi, '>');
output = output.replace(/&/gi, '&');
output = output.replace(/'/gi, "'");
var fieldArray = output.split('</head>');
if (fieldArray[1].search('class="short_text"') != -1) {
var tempResz = fieldArray[1].split('<span id=result_box class="short_text">');
} else if (fieldArray[1].search('class="medium_text"') != -1) {
var tempResz = fieldArray[1].split('<span id=result_box class="medium_text">');
} else {
var tempResz = fieldArray[1].split('<span id=result_box class="long_text">');
}
var kimenet = tempResz[1].split('</span></div>');
if (gTranslator._showpopuptext === false) {
var focusedWindow = document.commandDispatcher.focusedWindow;
var range = focusedWindow.getSelection().getRangeAt(0);
range.deleteContents();
range.insertNode(document.createTextNode(kezdospace + removeHTMLTags(kimenet[0]) + vegespace));
} else {
gTranslator.show(kezdospace + removeHTMLTags(kimenet[0]) + vegespace);
}
}
}
httpRequest = new XMLHttpRequest();
httpRequest.open("GET", fullUrl, true);
httpRequest.onload = infoReceived;
httpRequest.send(null);
if (gTranslator._showpopuptext === true)
this.show("正在获取翻译结果,请等待...");
else
XULBrowserWindow.statusTextField.label="正在获取翻译结果,请等待...";
} else { //ha a kijelolt szoveg hossza <=0 vagy >38000
var prompts = Components.classes["@mozilla.org/embedcomp/prompt-service;1"]
.getService(Components.interfaces.nsIPromptService);
prompts.alert(null, "Google Translator", "选中的文本不能超过38000个字符!");
}
},
show : function (res) {
var popup = document.getElementById("translationResult");
this.setValue(res);
this.sizeChange();
var node = document.getElementById("content");
if (!node) {
node = document.getElementById("messagepane");
}
if (this._timer)
clearTimeout(this._timer);
if (typeof popup.openPopup != 'undefined')
popup.openPopup(node, "overlap", 0, 0, true, false);
else
popup.showPopup(node, -1, -1, "popup", null, null);
setTimeout(function () {
gTranslator.sizeChange();
}, 0);
this._timer = setTimeout(function () {
popup.hidePopup();
}, 15000); //显示时间15秒
},
setValue : function (val) {
var label = document.getElementById("translationResultPopupLabel");
while (label.firstChild) {
label.removeChild(label.firstChild);
}
if (val != "")
label.appendChild(document.createTextNode(val));
},
sizeChange : function () {
var popup = document.getElementById("translationResult");
var box = document.getElementById("translationResultPopupBox");
popup.sizeTo(450, Math.max(box.boxObject.height * 1.0 + 15, 23));
},
copyToClipboard : function (e, aValue) {
if (e.button == 0) {
var clipid = Components.interfaces.nsIClipboard;
var clip = Components.classes['@mozilla.org/widget/clipboard;1'].getService(clipid);
if (!clip) {
return;
}
var trans = Components.classes['@mozilla.org/widget/transferable;1'].
createInstance(Components.interfaces.nsITransferable);
if (!trans) {
return;
}
var str = Components.classes['@mozilla.org/supports-string;1'].
createInstance(Components.interfaces.nsISupportsString);
str.data = aValue;
trans.setTransferData("text/unicode", str, aValue.length * 2);
clip.setData(trans, null, clipid.kGlobalClipboard);
} else if (e.button == 2) {
var popup = document.getElementById("translationResult");
clearTimeout(this._timer);
popup.hidePopup();
}
}
};
gTranslator.onLoad();