-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcontent_script.js
234 lines (221 loc) · 7.29 KB
/
content_script.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
/**
* Copyright 2020 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
((browser) => {
let DEBUG = false;
const log = (...args) => {
if (DEBUG) {
console.log(...args);
}
};
// Credits: https://stackoverflow.com/a/7381574/6255000
const snapSelectionToWord = (sel) => {
if (!sel.isCollapsed) {
// Detect if selection is backwards
const range = document.createRange();
range.setStart(sel.anchorNode, sel.anchorOffset);
range.setEnd(sel.focusNode, sel.focusOffset);
const direction = range.collapsed ?
['backward', 'forward'] :
['forward', 'backward'];
range.detach();
// modify() works on the focus of the selection
const endNode = sel.focusNode;
const endOffset = sel.focusOffset;
sel.collapse(sel.anchorNode, sel.anchorOffset);
sel.modify('move', direction[0], 'character');
sel.modify('move', direction[1], 'word');
sel.extend(endNode, endOffset);
sel.modify('extend', direction[1], 'character');
sel.modify('extend', direction[0], 'word');
}
return sel.toString().trim();
};
const getPreviousNode = (anchorNode) => {
let seenAnchorNode = false;
const treeWalker = document.createTreeWalker(
document.body,
NodeFilter.SHOW_TEXT,
{
acceptNode: (node) => {
if (node.isSameNode(anchorNode)) {
seenAnchorNode = true;
return NodeFilter.FILTER_SKIP;
}
if (seenAnchorNode) {
return NodeFilter.FILTER_SKIP;
}
return node.parentNode.offsetParent &&
node.nodeValue.replace(/\s/g, '') ?
NodeFilter.FILTER_ACCEPT :
NodeFilter.FILTER_SKIP;
},
},
);
let previousNode = null;
let currentNode = null;
while ((currentNode = treeWalker.nextNode())) {
previousNode = currentNode;
}
return previousNode;
};
const getNextNode = (focusNode) => {
let seenFocusNode = false;
const treeWalker = document.createTreeWalker(
document.body,
NodeFilter.SHOW_TEXT,
{
acceptNode: (node) => {
if (node.isSameNode(focusNode)) {
seenFocusNode = true;
return NodeFilter.FILTER_SKIP;
}
if (!seenFocusNode) {
return NodeFilter.FILTER_SKIP;
}
return node.parentNode.offsetParent &&
node.nodeValue.replace(/\s/g, '') ?
NodeFilter.FILTER_ACCEPT :
NodeFilter.FILTER_SKIP;
},
},
);
return treeWalker.nextNode();
};
const getClosestID = (root) => {
if (root.id) {
return root.id;
}
let seenRoot = false;
const treeWalker = document.createTreeWalker(
document.body,
NodeFilter.SHOW_ELEMENT,
{
acceptNode: (node) => {
if (node.isSameNode(root)) {
seenRoot = true;
}
return node.offsetParent && node.hasAttribute('id') && !seenRoot ?
NodeFilter.FILTER_ACCEPT :
NodeFilter.FILTER_SKIP;
},
},
);
let nodeWithID = null;
let currentNode = null;
while ((currentNode = treeWalker.nextNode())) {
nodeWithID = currentNode;
}
return nodeWithID ? nodeWithID.id : null;
};
const cleanText = (text) => {
// Replace with regular space.
return text.replace(/\u00A0/g, ' ');
};
const getText = (sendResponse) => {
const selection = window.getSelection();
const selectedText = snapSelectionToWord(selection);
let {anchorNode, anchorOffset, focusNode, focusOffset} = selection;
// If the selection is backward across nodes, swap the nodes.
if (
anchorNode.compareDocumentPosition(focusNode) ===
Node.DOCUMENT_POSITION_PRECEDING
) {
[anchorNode, focusNode] = [focusNode, anchorNode];
[anchorOffset, focusOffset] = [focusOffset, anchorOffset];
}
const pageText = document.body.innerText.trim();
const textBeforeSelection = anchorNode.textContent
.substr(0, anchorOffset)
.trim();
const textAfterSelection = focusNode.textContent.substr(focusOffset).trim();
const closestElementFragment = getClosestID(anchorNode.parentNode);
const previousNode = getPreviousNode(anchorNode);
const nextNode = getNextNode(focusNode);
const textNodeBeforeSelection = previousNode ?
previousNode.nodeType === 3 ?
previousNode.nodeValue :
previousNode.innerText :
'';
const textNodeAfterSelection = nextNode ?
nextNode.nodeType === 3 ?
nextNode.nodeValue :
nextNode.innerText :
'';
//Fetch filename
let fileurl = ''
if (closestElementFragment === "viewer") {
const relatedDiv = document.getElementById("attach-name");
if (relatedDiv) {
fileurl = relatedDiv.querySelector('a').getAttribute('id')
}
}
const data = {
selectedText: cleanText(selectedText),
pageText: cleanText(pageText),
textBeforeSelection: cleanText(textBeforeSelection),
textAfterSelection: cleanText(textAfterSelection),
textNodeBeforeSelection: cleanText(textNodeBeforeSelection),
textNodeAfterSelection: cleanText(textNodeAfterSelection),
closestElementFragment,
fileurl
};
log(data);
return data;
};
const reportSuccess = (url) => {
log(url);
const style = document.createElement('style');
document.head.append(style);
const sheet = style.sheet;
sheet.insertRule(`
::selection {
color: #000 !important;
background-color: #ffff00 !important;
}`);
// Need to force re-selection for the CSS to have an effect in Safari.
const selection = window.getSelection();
const range = selection.getRangeAt(0);
selection.removeAllRanges();
window.setTimeout(() => selection.addRange(range), 0);
window.setTimeout(() => style.remove(), 2000);
return true;
};
const reportFailure = () => {
window.queueMicrotask(() => {
alert(
`🛑 ${browser.i18n.getMessage(
'extension_name',
)}:\n${browser.i18n.getMessage('link_failure')}`,
);
});
return true;
};
browser.runtime.onMessage.addListener((request, _, sendResponse) => {
const message = request.message;
if (message === 'get-text') {
return sendResponse(getText());
} else if (message === 'success') {
return sendResponse(reportSuccess(request.data));
} else if (message === 'failure') {
return sendResponse(reportFailure());
} else if (message === 'debug') {
return sendResponse((DEBUG = request.data) || true);
} else if (message === 'ping') {
return sendResponse('pong');
}
});
// eslint-disable-next-line no-undef
})(chrome || browser);