-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathcontentscript.js
85 lines (77 loc) · 2.7 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
const init = (function init( // eslint-disable-line no-unused-vars
{
utils,
strategy,
location,
enums,
},
MutationSummary,
) {
let mutationObserver; // eslint-disable-line no-unused-vars
const onAnchorClicked = (e) => {
const a = e.currentTarget;
if (utils.shouldIgnore(a, strategy)) return;
if (e.which > 1 && e.which < 4) return;
e.preventDefault();
e.stopImmediatePropagation();
utils.sendMessage(
enums.LINK_CLICKED,
{
hostname: location.hostname,
anchorType: utils.determineAnchorType(a, location.origin, strategy),
anchorUrl: a.href,
},
);
};
const addClickHandlers = (anchors) => {
anchors.forEach((a) => {
a.addEventListener('click', onAnchorClicked);
});
};
const removeClickHandlers = (anchors) => {
anchors.forEach((a) => {
a.removeEventListener('click', onAnchorClicked);
});
};
utils.getOptions()
.then((options) => {
chrome.runtime.onMessage.addListener((msg) => {
const messageHandlers = {
[enums.SAVE_OPTIONS_SUCCEEDED]: (newOptions) => {
const [subdomain, domain] = utils.getSubDomainOfUrl(location.hostname);
const newPrefs = utils.getPrefs(newOptions, subdomain, domain);
const allAnchors = document.querySelectorAll('a');
if (newPrefs && !utils.isSleepTimerEnabled(newPrefs.expiration, Date.now())) {
addClickHandlers(allAnchors);
} else {
removeClickHandlers(allAnchors);
}
},
[enums.FEEDBACK_CLICKED]: () => {
const feedbackAnchor = document.createElement('a');
feedbackAnchor.setAttribute('href', 'mailto:[email protected]');
feedbackAnchor.setAttribute('target', '_blank');
feedbackAnchor.click();
},
};
messageHandlers[msg.type](msg.payload);
});
const [subdomain, domain] = utils.getSubDomainOfUrl(location.hostname);
const prefs = utils.getPrefs(options, subdomain, domain);
if (prefs && prefs.enabled && !utils.isSleepTimerEnabled(prefs.expiration, Date.now())) {
addClickHandlers(document.querySelectorAll('a'));
}
utils.sendMessage(enums.SET_ICON, { prefs }, () => console.log('prefs sent'));
mutationObserver = new MutationSummary({
callback: (summaryObjects) => {
if (prefs && prefs.enabled && !utils.isSleepTimerEnabled(prefs.expiration, Date.now())) {
addClickHandlers(summaryObjects[0].added);
}
},
queries: [
{ element: 'a' },
],
});
})
.catch(console.log);
}(window, MutationSummary)); // eslint-disable-line no-undef