forked from tin0312/walk-more-than-you-scroll
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcontent.js
58 lines (45 loc) · 1.62 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
/* global pixelToMeter, debounce, stats */
const liveCounter = document.createElement('div');
liveCounter.classList.add('scroll-counter');
document.body.appendChild(liveCounter);
const websiteDomain = window.location.hostname;
const initialScrollPosition = window.scrollY;
let lastScrollPosition = initialScrollPosition;
let scrollDistance = 0;
stats.getDomainDistance(websiteDomain).then((distance) => {
scrollDistance = distance;
updateLiveCounter(scrollDistance);
});
const updateScrollDistance = () => {
const scrollPosition = window.scrollY;
const distance = Math.abs(scrollPosition - lastScrollPosition);
lastScrollPosition = scrollPosition;
saveDistance(websiteDomain, distance);
scrollDistance += distance;
updateLiveCounter(scrollDistance);
};
const updateLiveCounter = (distance) => {
const distanceMeter = pixelToMeter(distance);
liveCounter.innerHTML = `${distanceMeter}m`;
};
window.addEventListener('scroll', updateScrollDistance);
/**
* Debounce saving scroll distance to local storage
*/
const saveDistance = (() => {
const DEBOUNCE_TIMEOUT = 1000;
let scrollDistance = 0;
const save = debounce(function (domain) {
stats.updateDistance(domain, scrollDistance).then(() => {
scrollDistance = 0;
});
}, DEBOUNCE_TIMEOUT);
return function (domain, distance) {
// chrome storage is unavailable if the content is invalidated
if (isContextInvalidated()) return;
scrollDistance += distance;
save(domain, distance);
};
})();
// if the extension is reloaded, the context is invalidated and the page needs to be reloaded
const isContextInvalidated = () => !chrome.runtime?.id;