-
Notifications
You must be signed in to change notification settings - Fork 137
/
content_script.js
4078 lines (3527 loc) · 136 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
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
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// prettier-ignore
(function () {
const jrDomain = "https://justread.link/";
let isPremium = false;
let jrSecret;
let jrOpenCount;
let hasBeenAskedForReview100 = false;
let hasBeenAskedForReview1000 = false;
let hasBeenAskedForReview10000 = false;
let hasBeenNotifiedOfSummarizer = false;
let removeOrigContent;
let chromeStorage, pageSelectedContainer;
chrome.storage.sync.get(null, function (result) {
chromeStorage = result || {};
// Allow content to be removed if enabled
if (chromeStorage["remove-orig-content"] !== false) {
removeOrigContent = true;
}
useText = chromeStorage["useText"];
launch();
});
/////////////////////////////////////
// Generic helper functions
/////////////////////////////////////
// Add :scope functionality to QS & QSA
(function (doc, proto) {
try {
// Check if browser supports :scope natively
doc.querySelector(":scope body");
} catch (err) {
// Polyfill native methods if it doesn't
["querySelector", "querySelectorAll"].forEach(function (method) {
const nativ = proto[method];
proto[method] = function (selectors) {
if (/(^|,)\s*:scope/.test(selectors)) {
// Only if selectors contains :scope
const id = this.id; // Remember current element id
this.id = "ID_" + Date.now(); // Assign new unique id
selectors = selectors.replace(/((^|,)\s*):scope/g, "$1#" + this.id); // Replace :scope with #ID
const result = doc[method](selectors);
this.id = id; // Restore previous id
return result;
} else {
return nativ.call(this, selectors); // Use native code for other selectors
}
};
});
}
})(window.document, Element.prototype);
function isEmpty(obj) {
return Object.keys(obj).length === 0;
}
// Mute a singular HTML5 element
function muteMe(elem) {
elem.muted = true;
elem.pause();
}
// Try to mute all video and audio elements on the page
function mutePage() {
document.querySelectorAll("video").forEach((video) => muteMe(video));
document.querySelectorAll("audio").forEach((audio) => muteMe(audio));
}
// Generate a random UUID (string)
// Example: 9ae68c40-0431-4031-afa0-3016ae50ad5d
function uuidv4() {
return ([1e7] + -1e3 + -4e3 + -8e3 + -1e11).replace(/[018]/g, (c) =>
(
c ^
(crypto.getRandomValues(new Uint8Array(1))[0] & (15 >> (c / 4)))
).toString(16)
);
}
function stylesheetToString(s) {
let text = "";
Array.from(s.cssRules).forEach((rule) => (text += rule.cssText));
return text;
}
function convertCssVariableToReadableValue(color) {
if (color.toLowerCase().indexOf('var(') !== -1) {
const regExp = /\(([^)]+)\)/;
const cssVar = regExp.exec(color)[1];
const computedStyles = getComputedStyle(document.getElementById("simple-article").contentWindow.document.body);
return computedStyles.getPropertyValue(cssVar);
}
return color;
}
/////////////////////////////////////
// State functions
/////////////////////////////////////
// User-selected text functionality
let last, userSelected;
function startSelectElement(doc) {
const pointerFunc = function (e) {
const elem = e.target;
if (last != elem) {
if (last != null) {
last.classList.remove("jr-hovered");
}
last = elem;
elem.classList.add("jr-hovered");
}
},
clickFunc = function (e) {
userSelected = e.target;
exitFunc();
},
escFunc = function (e) {
// Listen for the "Esc" key and exit if so
if (e.key === "Escape") exitFunc(true);
},
exitFunc = function (avoidLaunch) {
doc.removeEventListener("pointerover", pointerFunc);
doc.removeEventListener("click", clickFunc);
doc.removeEventListener("keydown", escFunc);
if (doc.querySelector(".jr-hovered") != null)
doc.querySelector(".jr-hovered").classList.remove("jr-hovered");
if (doc.getElementById("tempStyle") != null)
doc
.getElementById("tempStyle")
.parentElement.removeChild(doc.getElementById("tempStyle"));
useText = false;
if (avoidLaunch) return;
launch();
};
doc.addEventListener("pointerover", pointerFunc);
doc.addEventListener("click", clickFunc);
doc.addEventListener("keydown", escFunc);
doc.documentElement.focus();
// Add our styles temporarily
const tempStyle = doc.createElement("style");
tempStyle.id = "temp-style";
tempStyle.innerText =
".jr-hovered, .jr-hovered * { cursor: pointer !important; color: black !important; background-color: #2095f2 !important; }";
doc.head.appendChild(tempStyle);
}
// Similar to ^^ but for deletion once the article is open
function startDeleteElement(doc) {
const pointerFunc = function (e) {
const elem = e.target;
if (
!elem.classList.contains("simple-container") &&
!elem.classList.contains("simple-ui-container") &&
!elem.classList.contains("simple-control") &&
!elem.classList.contains("simple-add-comment") &&
!elem.classList.contains("simple-comments") &&
!elem.classList.contains("simple-edit") &&
elem.parentElement &&
elem.parentElement.classList &&
!(
elem.parentElement.classList.contains("simple-add-comment") ||
elem.parentElement.classList.contains("simple-control")
) &&
doc.body != elem &&
doc.documentElement != elem &&
elem.tagName !== "path" &&
elem.tagName !== "rect" &&
elem.tagName !== "polygon" &&
elem.tagName !== "PROGRESS"
) {
if (last != elem) {
if (last != null) {
last.classList.remove("jr-hovered");
}
last = elem;
elem.classList.add("jr-hovered");
}
}
},
clickFunc = function (e) {
selected = e.target;
if (
!selected.classList.contains("simple-container") &&
!selected.classList.contains("simple-ui-container") &&
!selected.classList.contains("simple-control") &&
!selected.classList.contains("simple-add-comment") &&
!selected.classList.contains("simple-comments") &&
!selected.classList.contains("simple-edit") &&
selected.parentElement.classList &&
!(
selected.parentElement.classList.contains("simple-add-comment") ||
selected.parentElement.classList.contains("simple-control")
) &&
doc.body != selected &&
doc.documentElement != selected &&
selected.tagName !== "path" &&
selected.tagName !== "rect" &&
selected.tagName !== "polygon" &&
selected.tagName !== "PROGRESS"
)
actionWithStack("delete", selected);
e.preventDefault();
},
escFunc = function (e) {
// Listen for the "Esc" key and exit if so
if (e.key === "Escape") exitFunc();
},
exitFunc = function () {
anchors.forEach(function (a) {
a.removeEventListener("click", anchorFunc);
});
doc.removeEventListener("pointerover", pointerFunc);
doc.removeEventListener("click", clickFunc);
doc.removeEventListener("keydown", escFunc);
[...iframes].forEach((elem) => (elem.style.pointerEvents = "auto"));
if (doc.querySelector(".jr-hovered") != null)
doc.querySelector(".jr-hovered").classList.remove("jr-hovered");
doc.body.classList.remove("simple-deleting");
userSelected = null;
sd.classList.remove("active");
sd.onclick = function () {
startDeleteElement(simpleArticleIframe);
};
},
anchorFunc = function (e) {
e.preventDefault();
};
const anchors = doc.querySelectorAll("a");
anchors.forEach(function (a) {
a.addEventListener("click", anchorFunc);
});
doc.body.classList.add("simple-deleting");
doc.addEventListener("pointerover", pointerFunc);
doc.addEventListener("click", clickFunc);
doc.addEventListener("keydown", escFunc);
const iframes = doc.querySelectorAll("iframe");
[...iframes].forEach((elem) => (elem.style.pointerEvents = "none"));
const sd = simpleArticleIframe.querySelector(".simple-delete");
sd.classList.add("active");
sd.onclick = function () {
exitFunc();
};
}
const stack = [];
function actionWithStack(actionName, elem, startText) {
hasSavedLink = false;
shareDropdown.classList.remove("active");
let actionObj;
if (actionName === "delete") {
elem.classList.remove("jr-hovered");
let parent = elem.parentElement;
actionObj = {
type: "delete",
index: Array.from(parent.children).indexOf(elem),
parent: parent,
elem: parent.removeChild(elem),
};
} else if (actionName === "edit") {
actionObj = {
type: "edit",
elem: elem,
text: startText,
};
}
if (actionName) {
stack.push(actionObj);
undoBtn.classList.add("shown");
}
updateSavedVersion();
getMeasurements(); // Update the scrollbar sizing
}
function popStack() {
let actionObj = stack.pop();
if (actionObj && actionObj.type === "delete") {
actionObj.parent.insertBefore(
actionObj.elem,
actionObj.parent.children[actionObj.index]
);
} else if (actionObj && actionObj.type === "edit") {
actionObj.elem.innerText = actionObj.text;
}
updateSavedVersion();
// If empty, hide undo button
if (stack.length === 0) {
undoBtn.classList.remove("shown");
}
getMeasurements(); // Update the scrollbar sizing
}
function updateSavedVersion() {
if (chromeStorage["backup"]) {
const data = {
url: window.location.href,
content: DOMPurify.sanitize(
simpleArticleIframe.querySelector(".content-container").innerHTML
),
};
if (
simpleArticleIframe.querySelector(".simple-comments").innerHTML !== ""
) {
data.savedComments = DOMPurify.sanitize(
simpleArticleIframe.querySelector(".simple-comments").innerHTML
);
data.savedCompactComments = DOMPurify.sanitize(
simpleArticleIframe.querySelector(".simple-compact-comments").innerHTML
);
}
chrome.storage.local.set({JRSavedPage: JSON.stringify(data)});
}
}
/////////////////////////////////////
// Chrome storage functions
/////////////////////////////////////
// Given a chrome storage object add them to our local stylsheet obj
function getStylesFromStorage(storage) {
for (let key in storage) {
if (key.substring(0, 3) === "jr-") {
// Get stylesheets in the new format
stylesheetObj[key.substring(3)] = storage[key];
}
}
}
// Set the chrome storage based on our stylesheet object
function setStylesOfStorage() {
for (let stylesheet in stylesheetObj) {
const obj = {};
obj["jr-" + stylesheet] = stylesheetObj[stylesheet];
chrome.storage.sync.set(obj);
}
}
/////////////////////////////////////
// Extension-related helper functions
/////////////////////////////////////
// From https://stackoverflow.com/a/14824756/2065702
function isRTL(s) {
const ltrChars =
"A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02B8\u0300-\u0590\u0800-\u1FFF" +
"\u2C00-\uFB1C\uFDFE-\uFE6F\uFEFD-\uFFFF",
rtlChars = "\u0591-\u07FF\uFB1D-\uFDFD\uFE70-\uFEFC",
rtlDirCheck = new RegExp("^[^" + ltrChars + "]*[" + rtlChars + "]");
return rtlDirCheck.test(s);
}
function checkElemForDate(elem, attrList, deleteMe) {
let myDate = false;
if (elem && checkAgainstBlacklist(elem, 3)) {
attrList.some((attr) => {
if (
elem[attr] &&
elem[attr] != "" && // Make sure it's not empty
elem[attr].split(" ").length < 10
) {
// Make sure the date isn't absurdly long
myDate = elem[attr];
if (deleteMe) {
elem.dataset.simpleDelete = true; // Flag it for removal later
}
return true;
}
});
}
return myDate;
}
function getJSONSchema(text) {
try {
return JSON.parse(text);
} catch (e) {
console.error("Invalid JSON schema");
return null;
}
}
function getArticleDate() {
// Make sure that the pageSelectedContainer isn't empty
if (pageSelectedContainer == null) pageSelectedContainer = document.body;
// Check to see if there's a date class
let date = false;
if (dateSelector && document.querySelector(dateSelector)) {
const elem = document.querySelector(dateSelector);
date = elem.innerText;
elem.dataset.simpleDelete = true; // Flag it for removal later
}
// Check schema first
let jsonld;
if (
!date &&
pageSelectedContainer.querySelector('script[type="application/ld+json"]')
) {
jsonld = getJSONSchema(
pageSelectedContainer.querySelector('script[type="application/ld+json"]')
.innerText
);
} else if (
!date &&
document.querySelector('script[type="application/ld+json"]')
) {
jsonld = getJSONSchema(
document.querySelector('script[type="application/ld+json"]').innerText
);
}
if (!date && jsonld) {
if (jsonld.dateModified) {
date = jsonld.dateModified;
} else if (jsonld.datePublished) {
date = jsonld.datePublished;
}
}
let toCheck = [];
if (!date) {
toCheck = [
[
pageSelectedContainer.querySelector('[itemprop="dateModified"]'),
["innerText"],
true,
],
[
pageSelectedContainer.querySelector('[itemprop="datePublished"]'),
["innerText"],
true,
],
[
pageSelectedContainer.querySelector('[class^="date"]'),
["innerText"],
true,
],
[
pageSelectedContainer.querySelector('[class*="-date"]'),
["innerText"],
true,
],
[
pageSelectedContainer.querySelector('[class*="_date"]'),
["innerText"],
true,
],
[
document.body.querySelector('[itemprop="dateModified"]'),
["innerText"],
false,
],
[
document.body.querySelector('[itemprop="datePublished"]'),
["innerText"],
false,
],
[document.body.querySelector('[class^="date"]'), ["innerText"], false],
[document.body.querySelector('[class*="-date"]'), ["innerText"], false],
[document.body.querySelector('[class*="_date"]'), ["innerText"], false],
[document.head.querySelector('meta[name^="date"]'), ["content"], false],
[document.head.querySelector('meta[name*="-date"]'), ["content"], false],
[
pageSelectedContainer.querySelector("time"),
["datetime", "innerText"],
true,
],
[document.body.querySelector("time"), ["datetime", "innerText"], false],
[
pageSelectedContainer.querySelector('[class *= "time"]'),
["datetime", "innerText"],
true,
],
[
document.body.querySelector('[class *= "time"]'),
["datetime", "innerText"],
false,
],
];
}
toCheck.some((checkObj) => {
if (!date && checkObj[0]) {
date = checkElemForDate(checkObj[0], checkObj[1], checkObj[2]);
if (date) return true;
}
});
if (date) {
return date
.replace(/on\s/gi, "")
.replace(/(?:\r\n|\r|\n)/gi, " ")
.replace(/[<]br[^>]*[>]/gi, " "); // Replace <br>, \n, and "on"
}
return "Unknown date";
}
function getArticleTitle() {
// Get the page's title
let title;
if (titleSelector && document.querySelector(titleSelector)) {
const elem = document.querySelector(titleSelector);
title = elem.innerText;
elem.dataset.simpleDelete = true; // Flag it for removal later
} else if (document.head.querySelector("title")) {
title = document.head.querySelector("title").innerText;
// Get the part before the first — if it exists
if (title.indexOf(" — ") > 0) {
return title.substr(0, title.indexOf(" — "));
}
// Get the part before the first – if it exists
if (title.indexOf(" – ") > 0) {
return title.substr(0, title.indexOf(" – "));
}
// Get the part before the first - if it exists DIFFERENT THAN ABOVE CHARACTER
if (title.indexOf(" - ") > 0) {
return title.substr(0, title.indexOf(" - "));
}
// Get the part before the first | if it exists
if (title.indexOf(" | ") > 0) {
return title.substr(0, title.indexOf(" | "));
}
// Get the part before the first : if it exists
if (title.indexOf(" : ") > 0) {
return title.substr(0, title.indexOf(" : "));
}
} else {
title = "Unknown title";
}
return title;
}
function getArticleAuthor() {
// Make sure that the pageSelectedContainer isn't empty
if (pageSelectedContainer == null) pageSelectedContainer = document.body;
let author = null;
let elem;
if (authorSelector && document.querySelector(authorSelector)) {
elem = document.querySelector(authorSelector);
author = elem.innerText;
elem.dataset.simpleDelete = true; // Flag it for removal later
}
// Check schema first
let jsonld;
if (
pageSelectedContainer.querySelector('script[type="application/ld+json"]')
) {
jsonld = getJSONSchema(
pageSelectedContainer.querySelector('script[type="application/ld+json"]')
.innerText
);
} else if (document.querySelector('script[type="application/ld+json"]')) {
jsonld = getJSONSchema(
document.querySelector('script[type="application/ld+json"]').innerText
);
}
if (author === null && jsonld) {
if (jsonld.author) {
if (typeof jsonld.author === "string") {
author = jsonld.author;
} else if (typeof jsonld.author.name === "string") {
author = jsonld.author.name;
}
}
}
// Check to see if there's an author itemprop in the article
elem = pageSelectedContainer.querySelector('[itemprop="author"]');
if (author === null && elem) {
if (
elem.innerText.split(/\s+/).length < 5 &&
elem.innerText.replace(/\s/g, "") !== ""
) {
elem.dataset.simpleDelete = true; // Flag it for removal later
author = elem.innerText;
}
}
// Check to see if there's an author itemprop in the page
elem = document.body.querySelector('[itemprop="author"]');
if (author === null && elem) {
if (
elem.innerText.split(/\s+/).length < 5 &&
elem.innerText.replace(/\s/g, "") !== ""
) {
author = elem.innerText;
}
}
// Check to see if there's an author rel in the article
elem = pageSelectedContainer.querySelector('[rel*="author"]');
if (author === null && elem) {
if (
elem.innerText.split(/\s+/).length < 5 &&
elem.innerText.replace(/\s/g, "") !== ""
) {
elem.dataset.simpleDelete = true; // Flag it for removal later
author = elem.innerText;
}
}
// Check to see if there's an author class
elem = pageSelectedContainer.querySelector('[class*="author"]');
if (author === null && elem && checkAgainstBlacklist(elem, 3)) {
if (
elem.innerText.split(/\s+/).length < 5 &&
elem.innerText.replace(/\s/g, "") !== ""
) {
elem.dataset.simpleDelete = true; // Flag it for removal later
author = elem.innerText;
}
}
elem = document.head.querySelector('meta[name*="author"]');
// Check to see if there is an author available in the meta, if so get it
if (author === null && elem) author = elem.getAttribute("content");
// Check to see if there's an author rel in the body
elem = document.body.querySelectorAll('[rel*="author"]');
elem.forEach((e) => {
if (author === null && e) {
if (
e.innerText.split(/\s+/).length < 5 &&
e.innerText.replace(/\s/g, "") !== ""
) {
author = e.innerText;
}
}
});
elem = document.body.querySelector('[class*="author"]');
if (author === null && elem && checkAgainstBlacklist(elem, 3)) {
if (
elem.innerText.split(/\s+/).length < 6 &&
elem.innerText.replace(/\s/g, "") !== ""
) {
author = elem.innerText;
}
}
if (author !== null && author) {
// If it's all caps, try to properly capitalize it
if (author === author.toUpperCase()) {
const words = author.split(" "),
wordsLength = words.length;
for (let i = 0; i < wordsLength; i++) {
if (words[i].length < 3 && i != 0 && i != wordsLength)
words[i] =
words[
i
].toLowerCase(); // Assume it's something like "de", "da", "van" etc.
else
words[i] =
words[i].charAt(0).toUpperCase() + words[i].substr(1).toLowerCase();
}
author = words.join(" ");
}
return author.replace(/by\s/gi, ""); // Replace "by"
}
return "Unknown author";
}
function getArticleContainer() {
let selectedContainer;
if (contentSelector && document.querySelector(contentSelector)) {
selectedContainer = document.querySelector(contentSelector);
} else if (document.head.querySelector("meta[name='articleBody'")) {
selectedContainer = document.createElement("div");
selectedContainer.innerHTML = DOMPurify.sanitize(
document.head
.querySelector("meta[name='articleBody'")
.getAttribute("content")
);
} else {
const numWordsOnPage = document.body.innerText.match(/\S+/g).length;
let ps = document.body.querySelectorAll("p");
// Find the paragraphs with the most words in it
let pWithMostWords = document.body,
highestWordCount = 0;
if (ps.length === 0) {
ps = document.body.querySelectorAll("div");
}
ps.forEach((p) => {
if (
checkAgainstBlacklist(p, 3) && // Make sure it's not in our blacklist
p.offsetHeight !== 0
) {
// Make sure it's visible on the regular page
const myInnerText = p.innerText.match(/\S+/g);
if (myInnerText) {
const wordCount = myInnerText.length;
if (wordCount > highestWordCount) {
highestWordCount = wordCount;
pWithMostWords = p;
}
}
}
// Remove elements in JR that were hidden on the original page
if (p.offsetHeight === 0) {
p.dataset.simpleDelete = true;
}
});
// Keep selecting more generally until over 2/5th of the words on the page have been selected
selectedContainer = pWithMostWords;
let wordCountSelected = highestWordCount;
while (
wordCountSelected / numWordsOnPage < 0.4 &&
selectedContainer != document.body &&
selectedContainer.parentElement.innerText
) {
selectedContainer = selectedContainer.parentElement;
wordCountSelected = selectedContainer.innerText.match(/\S+/g).length;
}
// Make sure a single p tag is not selected
if (selectedContainer.tagName === "P") {
selectedContainer = selectedContainer.parentElement;
}
}
return selectedContainer;
}
// Remove what we added (besides styles)
function closeOverlay() {
// Refresh the page if the content has been removed
if (removeOrigContent) {
const url = new URL(window.location);
url.searchParams.delete("jr");
window.location.replace(url);
}
// Remove the GUI if it is open
if (datGUI) {
datGUI.destroy();
datGUI = undefined;
}
window.removeEventListener("resize", hideToolbar);
// Fade out
simpleArticle.classList.add("simple-fade-up");
// Remove some general listeners
simpleArticleIframe.removeEventListener("mouseup", handleEnd);
simpleArticleIframe.removeEventListener("touchend", handleEnd);
simpleArticleIframe.removeEventListener("mousemove", handleMouseMove);
// Reset our variables
pageSelectedContainer = null;
userSelected = null;
simpleArticleIframe = undefined;
editBar = undefined;
chromeStorage = undefined;
setTimeout(function () {
// Enable scroll
document.documentElement.classList.remove("simple-no-scroll");
// Update our background script
chrome.runtime.sendMessage({ lastClosed: Date.now() });
// Remove our overlay
simpleArticle.parentElement.removeChild(simpleArticle);
simpleArticle = undefined;
}, 100); // Make sure we can animate it
}
// Handle link clicks
function linkListener(e) {
if (!simpleArticleIframe.body.classList.contains("simple-deleting")) {
// Don't change the top most if it's not in the current window
if (
e.ctrlKey ||
e.shiftKey ||
e.metaKey ||
(e.button && e.button == 1) ||
this.target === "about:blank" ||
this.target === "_blank"
) {
return; // Do nothing
}
// Don't change the top most if it's referencing an anchor in the article
const hrefArr = this.href.split("#");
if (
hrefArr.length < 2 || // No anchor
(hrefArr[0] !== top.window.location.href.split("#")[0] && // Anchored to an ID on another page
hrefArr[0] !== "about:blank" &&
hrefArr[0] !== "_blank") ||
(simpleArticleIframe.getElementById(hrefArr[1]) == null && // The element is not in the article section
simpleArticleIframe.querySelector("a[name='" + hrefArr[1] + "']") ==
null &&
hrefArr[1] !== "_")
) {
top.window.location.href = this.href; // Regular link
} else {
// Anchored to an element in the article
e.preventDefault();
e.stopPropagation();
if (hrefArr[1].startsWith("jr-")) {
simpleArticleIframe.getElementById(hrefArr[1]).scrollIntoView(true);
let backArrow = simpleArticleIframe.querySelector(
this.id + " .back-to-ref"
);
backArrow.dataset.scrollPos = simpleArticleIframe.scrollTop;
} else {
top.window.location.hash = hrefArr[1];
simpleArticleIframe.defaultView.location.hash = hrefArr[1];
}
}
}
}
// Check given item against blacklist, return null if in blacklist
const blacklist = ["comment"];
function checkAgainstBlacklist(elem, level) {
if (elem && elem != null) {
const className = elem.className,
id = elem.id;
const isBlackListed = blacklist
.map((item) => {
if (
(typeof className === "string" && className.indexOf(item) >= 0) ||
(typeof id === "string" && id.indexOf(item) >= 0)
) {
return true;
}
})
.filter((item) => item)[0];
if (isBlackListed) {
return null;
}
const parent = elem.parentElement;
if (level > 0 && parent && !parent.isSameNode(document.body)) {
return checkAgainstBlacklist(parent, --level);
}
}
return elem;
}
// See if an element is part of the selectable content
function isContentElem(elem) {
if (
simpleArticleIframe
.querySelector(".simple-article-container")
.contains(elem)
)
return true;
else return false;
}
/////////////////////////////////////
// Extension-related adder functions
/////////////////////////////////////
function checkPremium() {
// Check if premium
if (
chromeStorage.jrSecret &&
// Limit API calls on open to just 1 per day
(typeof chromeStorage.jrLastChecked === "undefined" ||
chromeStorage.jrLastChecked === "" ||
Date.now() - chromeStorage.jrLastChecked > 86400000)
) {
chrome.storage.sync.set({ jrLastChecked: Date.now() });
jrSecret = chromeStorage.jrSecret;
fetch(jrDomain + "checkPremium", {
mode: "cors",
method: "POST",
headers: { "Content-type": "application/json; charset=UTF-8" },
body: JSON.stringify({
jrSecret: jrSecret,
}),
})
.then(function (response) {
if (!response.ok) throw response;
else return response.text();
})
.then((response) => {
isPremium = response === "true";
chrome.storage.sync.set({ isPremium: isPremium });
afterPremium();
})
.catch((err) => console.error(`Fetch Error =\n`, err));
} else {
isPremium = chromeStorage.isPremium ? chromeStorage.isPremium : false;
jrSecret = chromeStorage.jrSecret ? chromeStorage.jrSecret : false;
afterPremium();
}
}
function afterPremium() {
// Collect all of our stylesheets in our object
getStylesFromStorage(chromeStorage);
// Check to see if the default stylesheet needs to be updated
let needsUpdate = false;
let versionResult = chromeStorage["stylesheet-version"];
// If the user has a version of the stylesheets and it is less than the current one, update it
if (
typeof versionResult === "undefined" ||
versionResult < stylesheetVersion
) {
chrome.storage.sync.set({ "stylesheet-version": stylesheetVersion });
needsUpdate = true;
}
if (
isEmpty(stylesheetObj) || // Not found, so we add our default
needsUpdate
) {
// Update the default stylesheet if it's on a previous version
// Open the default CSS file and save it to our object
let xhr = new XMLHttpRequest();
xhr.open("GET", chrome.runtime.getURL("default-styles.css"), true);
xhr.onreadystatechange = function () {
if (xhr.readyState == XMLHttpRequest.DONE && xhr.status == 200) {
// Save the file's contents to our object
stylesheetObj["default-styles.css"] = xhr.responseText;