-
Notifications
You must be signed in to change notification settings - Fork 0
/
contentScript.js
747 lines (604 loc) · 19.6 KB
/
contentScript.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
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
// run when page loads, substute the words
chrome.storage.sync.get(null, (wordsDict) => {
var parentArray = wordsDict['wordsList'];
if ( parentArray === undefined ) {
parentArray = []
}
for(var i = 0; i < parentArray.length; i++){
var fromWord = parentArray[i][0], toWord = parentArray[i][1];
// console.log(fromWord, toWord);
// document.body.innerHTML = document.body.innerHTML.replace(new RegExp(fromWord, 'gi'), toWord);
findAndReplaceDOMText( document.body, {
preset: 'prose',
find: fromWord,
replace: toWord
})
}
});
// listen for messages from the popup
chrome.runtime.onMessage.addListener(
(request, sender, sendResponse) => {
// console.log(request.type);
if (request.type == "addWords"){
addWord(request.fromWord, request.toWord);
location.reload();
}
else if (request.type == "clear"){
clearStorage();
location.reload();
}
else if (request.type == "displayAll"){
displayAll()
}
var vocabSize = 0;
getVocabSize()
.then( response => {
sendResponse({vocabSize: response})
}).catch( err => {
sendResponse({vocabSize: 0})
})
return true;
});
async function getVocabSize() {
var allWords = await getStorageValue("wordsList");
allWords = allWords["wordsList"];
if ( allWords === undefined ) {
allWords = []
}
// console.log(allWords.length);
return allWords.length
}
async function addWord(fromWord, toWord) {
// fetch allWords using chrome storage api
var allWords = await getStorageValue("wordsList");
allWords = allWords["wordsList"];
// clear all words
await clearStorage();
// set new list of words (made using previous words and current input from popus)
await setStorageValue(allWords, fromWord, toWord);
}
async function getStorageValue(key) {
return new Promise((resolve, reject) => {
try {
chrome.storage.sync.get(key, (value) => {
resolve(value);
})
}
catch (ex) {
reject(ex);
}
});
}
async function setStorageValue(allWords, fromWord, toWord) {
new Promise((resolve, reject) => {
if ( allWords === undefined ) {
allWords = []
}
allWords = [...allWords, [fromWord, toWord]]
chrome.storage.sync.set({wordsList: allWords});
});
}
async function clearStorage() {
new Promise((resolve, reject) => {
chrome.storage.sync.clear();
});
}
// for debugging
async function displayAll() {
// run when page loads
var allWords = await getStorageValue("wordsList");
var parentArray = allWords["wordsList"];
if ( parentArray === undefined ) {
parentArray = [];
}
for(var i = 0; i < parentArray.length; i++){
var fromWord = parentArray[i][0], toWord = parentArray[i][1];
console.log(fromWord, toWord);
}
}
// TODO: display all currently logs in console, print it in new page or in the popup.
// Below is the method to replace text in an unobrusive manner in the HTML page
/**
* findAndReplaceDOMText v 0.4.6
* @author James Padolsey http://james.padolsey.com
* @license http://unlicense.org/UNLICENSE
*
* Matches the text of a DOM node against a regular expression
* and replaces each match (or node-separated portions of the match)
* in the specified element.
*/
(function (root, factory) {
if (typeof module === 'object' && module.exports) {
// Node/CommonJS
module.exports = factory();
} else if (typeof define === 'function' && define.amd) {
// AMD. Register as an anonymous module.
define(factory);
} else {
// Browser globals
root.findAndReplaceDOMText = factory();
}
}(this, function factory() {
var PORTION_MODE_RETAIN = 'retain';
var PORTION_MODE_FIRST = 'first';
var doc = document;
var hasOwn = {}.hasOwnProperty;
function escapeRegExp(s) {
return String(s).replace(/([.*+?^=!:${}()|[\]\/\\])/g, '\\$1');
}
function exposed() {
// Try deprecated arg signature first:
return deprecated.apply(null, arguments) || findAndReplaceDOMText.apply(null, arguments);
}
function deprecated(regex, node, replacement, captureGroup, elFilter) {
if ((node && !node.nodeType) && arguments.length <= 2) {
return false;
}
var isReplacementFunction = typeof replacement == 'function';
if (isReplacementFunction) {
replacement = (function(original) {
return function(portion, match) {
return original(portion.text, match.startIndex);
};
}(replacement));
}
// Awkward support for deprecated argument signature (<0.4.0)
var instance = findAndReplaceDOMText(node, {
find: regex,
wrap: isReplacementFunction ? null : replacement,
replace: isReplacementFunction ? replacement : '$' + (captureGroup || '&'),
prepMatch: function(m, mi) {
// Support captureGroup (a deprecated feature)
if (!m[0]) throw 'findAndReplaceDOMText cannot handle zero-length matches';
if (captureGroup > 0) {
var cg = m[captureGroup];
m.index += m[0].indexOf(cg);
m[0] = cg;
}
m.endIndex = m.index + m[0].length;
m.startIndex = m.index;
m.index = mi;
return m;
},
filterElements: elFilter
});
exposed.revert = function() {
return instance.revert();
};
return true;
}
/**
* findAndReplaceDOMText
*
* Locates matches and replaces with replacementNode
*
* @param {Node} node Element or Text node to search within
* @param {RegExp} options.find The regular expression to match
* @param {String|Element} [options.wrap] A NodeName, or a Node to clone
* @param {String} [options.wrapClass] A classname to append to the wrapping element
* @param {String|Function} [options.replace='$&'] What to replace each match with
* @param {Function} [options.filterElements] A Function to be called to check whether to
* process an element. (returning true = process element,
* returning false = avoid element)
*/
function findAndReplaceDOMText(node, options) {
return new Finder(node, options);
}
exposed.NON_PROSE_ELEMENTS = {
br:1, hr:1,
// Media / Source elements:
script:1, style:1, img:1, video:1, audio:1, canvas:1, svg:1, map:1, object:1,
// Input elements
input:1, textarea:1, select:1, option:1, optgroup: 1, button:1
};
exposed.NON_CONTIGUOUS_PROSE_ELEMENTS = {
// Elements that will not contain prose or block elements where we don't
// want prose to be matches across element borders:
// Block Elements
address:1, article:1, aside:1, blockquote:1, dd:1, div:1,
dl:1, fieldset:1, figcaption:1, figure:1, footer:1, form:1, h1:1, h2:1, h3:1,
h4:1, h5:1, h6:1, header:1, hgroup:1, hr:1, main:1, nav:1, noscript:1, ol:1,
output:1, p:1, pre:1, section:1, ul:1,
// Other misc. elements that are not part of continuous inline prose:
br:1, li: 1, summary: 1, dt:1, details:1, rp:1, rt:1, rtc:1,
// Media / Source elements:
script:1, style:1, img:1, video:1, audio:1, canvas:1, svg:1, map:1, object:1,
// Input elements
input:1, textarea:1, select:1, option:1, optgroup:1, button:1,
// Table related elements:
table:1, tbody:1, thead:1, th:1, tr:1, td:1, caption:1, col:1, tfoot:1, colgroup:1
};
exposed.NON_INLINE_PROSE = function(el) {
return hasOwn.call(exposed.NON_CONTIGUOUS_PROSE_ELEMENTS, el.nodeName.toLowerCase());
};
// Presets accessed via `options.preset` when calling findAndReplaceDOMText():
exposed.PRESETS = {
prose: {
forceContext: exposed.NON_INLINE_PROSE,
filterElements: function(el) {
return !hasOwn.call(exposed.NON_PROSE_ELEMENTS, el.nodeName.toLowerCase());
}
}
};
exposed.Finder = Finder;
/**
* Finder -- encapsulates logic to find and replace.
*/
function Finder(node, options) {
var preset = options.preset && exposed.PRESETS[options.preset];
options.portionMode = options.portionMode || PORTION_MODE_RETAIN;
if (preset) {
for (var i in preset) {
if (hasOwn.call(preset, i) && !hasOwn.call(options, i)) {
options[i] = preset[i];
}
}
}
this.node = node;
this.options = options;
// Enable match-preparation method to be passed as option:
this.prepMatch = options.prepMatch || this.prepMatch;
this.reverts = [];
this.matches = this.search();
if (this.matches.length) {
this.processMatches();
}
}
Finder.prototype = {
/**
* Searches for all matches that comply with the instance's 'match' option
*/
search: function() {
var match;
var matchIndex = 0;
var offset = 0;
var regex = this.options.find;
var textAggregation = this.getAggregateText();
var matches = [];
var self = this;
regex = typeof regex === 'string' ? RegExp(escapeRegExp(regex), 'g') : regex;
matchAggregation(textAggregation);
function matchAggregation(textAggregation) {
for (var i = 0, l = textAggregation.length; i < l; ++i) {
var text = textAggregation[i];
if (typeof text !== 'string') {
// Deal with nested contexts: (recursive)
matchAggregation(text);
continue;
}
if (regex.global) {
while (match = regex.exec(text)) {
matches.push(self.prepMatch(match, matchIndex++, offset));
}
} else {
if (match = text.match(regex)) {
matches.push(self.prepMatch(match, 0, offset));
}
}
offset += text.length;
}
}
return matches;
},
/**
* Prepares a single match with useful meta info:
*/
prepMatch: function(match, matchIndex, characterOffset) {
if (!match[0]) {
throw new Error('findAndReplaceDOMText cannot handle zero-length matches');
}
match.endIndex = characterOffset + match.index + match[0].length;
match.startIndex = characterOffset + match.index;
match.index = matchIndex;
return match;
},
/**
* Gets aggregate text within subject node
*/
getAggregateText: function() {
var elementFilter = this.options.filterElements;
var forceContext = this.options.forceContext;
return getText(this.node);
/**
* Gets aggregate text of a node without resorting
* to broken innerText/textContent
*/
function getText(node) {
if (node.nodeType === Node.TEXT_NODE) {
return [node.data];
}
if (elementFilter && !elementFilter(node)) {
return [];
}
var txt = [''];
var i = 0;
if (node = node.firstChild) do {
if (node.nodeType === Node.TEXT_NODE) {
txt[i] += node.data;
continue;
}
var innerText = getText(node);
if (
forceContext &&
node.nodeType === Node.ELEMENT_NODE &&
(forceContext === true || forceContext(node))
) {
txt[++i] = innerText;
txt[++i] = '';
} else {
if (typeof innerText[0] === 'string') {
// Bridge nested text-node data so that they're
// not considered their own contexts:
// I.e. ['some', ['thing']] -> ['something']
txt[i] += innerText.shift();
}
if (innerText.length) {
txt[++i] = innerText;
txt[++i] = '';
}
}
} while (node = node.nextSibling);
return txt;
}
},
/**
* Steps through the target node, looking for matches, and
* calling replaceFn when a match is found.
*/
processMatches: function() {
var matches = this.matches;
var node = this.node;
var elementFilter = this.options.filterElements;
var startPortion,
endPortion,
innerPortions = [],
curNode = node,
match = matches.shift(),
atIndex = 0, // i.e. nodeAtIndex
matchIndex = 0,
portionIndex = 0,
doAvoidNode,
nodeStack = [node];
out: while (true) {
if (curNode.nodeType === Node.TEXT_NODE) {
if (!endPortion && curNode.length + atIndex >= match.endIndex) {
// We've found the ending
// (Note that, in the case of a single portion, it'll be an
// endPortion, not a startPortion.)
endPortion = {
node: curNode,
index: portionIndex++,
text: curNode.data.substring(match.startIndex - atIndex, match.endIndex - atIndex),
// If it's the first match (atIndex==0) we should just return 0
indexInMatch: atIndex === 0 ? 0 : atIndex - match.startIndex,
indexInNode: match.startIndex - atIndex,
endIndexInNode: match.endIndex - atIndex,
isEnd: true
};
} else if (startPortion) {
// Intersecting node
innerPortions.push({
node: curNode,
index: portionIndex++,
text: curNode.data,
indexInMatch: atIndex - match.startIndex,
indexInNode: 0 // always zero for inner-portions
});
}
if (!startPortion && curNode.length + atIndex > match.startIndex) {
// We've found the match start
startPortion = {
node: curNode,
index: portionIndex++,
indexInMatch: 0,
indexInNode: match.startIndex - atIndex,
endIndexInNode: match.endIndex - atIndex,
text: curNode.data.substring(match.startIndex - atIndex, match.endIndex - atIndex)
};
}
atIndex += curNode.data.length;
}
doAvoidNode = curNode.nodeType === Node.ELEMENT_NODE && elementFilter && !elementFilter(curNode);
if (startPortion && endPortion) {
curNode = this.replaceMatch(match, startPortion, innerPortions, endPortion);
// processMatches has to return the node that replaced the endNode
// and then we step back so we can continue from the end of the
// match:
atIndex -= (endPortion.node.data.length - endPortion.endIndexInNode);
startPortion = null;
endPortion = null;
innerPortions = [];
match = matches.shift();
portionIndex = 0;
matchIndex++;
if (!match) {
break; // no more matches
}
} else if (
!doAvoidNode &&
(curNode.firstChild || curNode.nextSibling)
) {
// Move down or forward:
if (curNode.firstChild) {
nodeStack.push(curNode);
curNode = curNode.firstChild;
} else {
curNode = curNode.nextSibling;
}
continue;
}
// Move forward or up:
while (true) {
if (curNode.nextSibling) {
curNode = curNode.nextSibling;
break;
}
curNode = nodeStack.pop();
if (curNode === node) {
break out;
}
}
}
},
/**
* Reverts ... TODO
*/
revert: function() {
// Reversion occurs backwards so as to avoid nodes subsequently
// replaced during the matching phase (a forward process):
for (var l = this.reverts.length; l--;) {
this.reverts[l]();
}
this.reverts = [];
},
prepareReplacementString: function(string, portion, match) {
var portionMode = this.options.portionMode;
if (
portionMode === PORTION_MODE_FIRST &&
portion.indexInMatch > 0
) {
return '';
}
string = string.replace(/\$(\d+|&|`|')/g, function($0, t) {
var replacement;
switch(t) {
case '&':
replacement = match[0];
break;
case '`':
replacement = match.input.substring(0, match.startIndex);
break;
case '\'':
replacement = match.input.substring(match.endIndex);
break;
default:
replacement = match[+t] || '';
}
return replacement;
});
if (portionMode === PORTION_MODE_FIRST) {
return string;
}
if (portion.isEnd) {
return string.substring(portion.indexInMatch);
}
return string.substring(portion.indexInMatch, portion.indexInMatch + portion.text.length);
},
getPortionReplacementNode: function(portion, match) {
var replacement = this.options.replace || '$&';
var wrapper = this.options.wrap;
var wrapperClass = this.options.wrapClass;
if (wrapper && wrapper.nodeType) {
// Wrapper has been provided as a stencil-node for us to clone:
var clone = doc.createElement('div');
clone.innerHTML = wrapper.outerHTML || new XMLSerializer().serializeToString(wrapper);
wrapper = clone.firstChild;
}
if (typeof replacement == 'function') {
replacement = replacement(portion, match);
if (replacement && replacement.nodeType) {
return replacement;
}
return doc.createTextNode(String(replacement));
}
var el = typeof wrapper == 'string' ? doc.createElement(wrapper) : wrapper;
if (el && wrapperClass) {
el.className = wrapperClass;
}
replacement = doc.createTextNode(
this.prepareReplacementString(
replacement, portion, match
)
);
if (!replacement.data) {
return replacement;
}
if (!el) {
return replacement;
}
el.appendChild(replacement);
return el;
},
replaceMatch: function(match, startPortion, innerPortions, endPortion) {
var matchStartNode = startPortion.node;
var matchEndNode = endPortion.node;
var precedingTextNode;
var followingTextNode;
if (matchStartNode === matchEndNode) {
var node = matchStartNode;
if (startPortion.indexInNode > 0) {
// Add `before` text node (before the match)
precedingTextNode = doc.createTextNode(node.data.substring(0, startPortion.indexInNode));
node.parentNode.insertBefore(precedingTextNode, node);
}
// Create the replacement node:
var newNode = this.getPortionReplacementNode(
endPortion,
match
);
node.parentNode.insertBefore(newNode, node);
if (endPortion.endIndexInNode < node.length) { // ?????
// Add `after` text node (after the match)
followingTextNode = doc.createTextNode(node.data.substring(endPortion.endIndexInNode));
node.parentNode.insertBefore(followingTextNode, node);
}
node.parentNode.removeChild(node);
this.reverts.push(function() {
if (precedingTextNode === newNode.previousSibling) {
precedingTextNode.parentNode.removeChild(precedingTextNode);
}
if (followingTextNode === newNode.nextSibling) {
followingTextNode.parentNode.removeChild(followingTextNode);
}
newNode.parentNode.replaceChild(node, newNode);
});
return newNode;
} else {
// Replace matchStartNode -> [innerMatchNodes...] -> matchEndNode (in that order)
precedingTextNode = doc.createTextNode(
matchStartNode.data.substring(0, startPortion.indexInNode)
);
followingTextNode = doc.createTextNode(
matchEndNode.data.substring(endPortion.endIndexInNode)
);
var firstNode = this.getPortionReplacementNode(
startPortion,
match
);
var innerNodes = [];
for (var i = 0, l = innerPortions.length; i < l; ++i) {
var portion = innerPortions[i];
var innerNode = this.getPortionReplacementNode(
portion,
match
);
portion.node.parentNode.replaceChild(innerNode, portion.node);
this.reverts.push((function(portion, innerNode) {
return function() {
innerNode.parentNode.replaceChild(portion.node, innerNode);
};
}(portion, innerNode)));
innerNodes.push(innerNode);
}
var lastNode = this.getPortionReplacementNode(
endPortion,
match
);
matchStartNode.parentNode.insertBefore(precedingTextNode, matchStartNode);
matchStartNode.parentNode.insertBefore(firstNode, matchStartNode);
matchStartNode.parentNode.removeChild(matchStartNode);
matchEndNode.parentNode.insertBefore(lastNode, matchEndNode);
matchEndNode.parentNode.insertBefore(followingTextNode, matchEndNode);
matchEndNode.parentNode.removeChild(matchEndNode);
this.reverts.push(function() {
precedingTextNode.parentNode.removeChild(precedingTextNode);
firstNode.parentNode.replaceChild(matchStartNode, firstNode);
followingTextNode.parentNode.removeChild(followingTextNode);
lastNode.parentNode.replaceChild(matchEndNode, lastNode);
});
return lastNode;
}
}
};
return exposed;
}));