-
Notifications
You must be signed in to change notification settings - Fork 0
/
content.js
112 lines (91 loc) · 2.49 KB
/
content.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
/* jshint multistr:true */
/* jshint undef:true */
/* global document, window, XMLHttpRequest */
/* global chrome */
var HerrRikai = (function() {
var _dictionary = {};
var _ready = false;
var POPUP_NAME = 'herr_rikai_popup';
var load_dictionary = function() {
var req = new XMLHttpRequest();
req.open("GET", chrome.extension.getURL('dict.json'), false);
req.send(null);
_dictionary = JSON.parse(req.responseText);
};
var popup = function(txt, x, y) {
var el = document.getElementById(POPUP_NAME);
el.innerHTML = txt;
el.style.top = y+'px';
el.style.left = x+'px';
el.style.opacity = 1;
};
var hide = function() {
document.getElementById(POPUP_NAME).style.opacity = 0;
document.getElementById(POPUP_NAME).style.top = '-1000px';
};
var clean = function(word) {
return word.replace('.','').replace(',','').replace(' ','');
};
var lookup = function(word) {
if(!word) return;
return _dictionary[word];
};
var mousemove = function(e) {
var range = null;
var textNode = null;
var offset = null;
if (document.caretPositionFromPoint) {
range = document.caretPositionFromPoint(e.clientX, e.clientY);
textNode = range.offsetNode;
offset = range.offset;
} else if (document.caretRangeFromPoint) {
range = document.caretRangeFromPoint(e.clientX, e.clientY);
textNode = range.startContainer;
offset = range.startOffset;
}
var str = textNode.textContent;
var start = offset;
var end = offset;
var delimiters = ' ,.\n":;-/\\!?';
while(start >= 0 && delimiters.indexOf(str[start]) < 0) {
start--;
}
start++;
while(end <= str.length && delimiters.indexOf(str[end]) < 0) {
end++;
}
var word = str.substring(start, end).toLowerCase();
var trans = lookup(clean(word));
var selection = window.getSelection();
if(typeof(trans) != 'undefined') {
popup(word+'<br/>'+trans, e.clientX, e.pageY + 20);
range.setStart(textNode, start);
range.setEnd(textNode, end);
selection.removeAllRanges();
selection.addRange(range);
}
else {
hide();
selection.removeAllRanges();
}
};
var init = function() {
if(_ready) {
return;
}
load_dictionary();
var popup = document.createElement('div');
popup.id = 'herr_rikai_popup';
document.body.appendChild(popup);
document.addEventListener('mousemove',mousemove);
_ready = true;
};
return {
messageHandler: function(message, sender) {
if(message.action == 'load') {
init();
}
}
};
})();
chrome.runtime.onMessage.addListener(HerrRikai.messageHandler);