-
Notifications
You must be signed in to change notification settings - Fork 0
/
time-on-page.html
83 lines (59 loc) · 2.83 KB
/
time-on-page.html
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
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>TOP</title>
<style>
body { text-align: center; }
h1, h3 { font-family: Arial; }
mark { font-size: large; }
</style>
</head>
<body>
<h1>Time on Page</h1>
<h3>This code example can be used to determine the amount of time (in seconds) user spent on the page, before he closes it.</h3>
<p>We've created an dummy API: <code><a href="https://topapi.free.beeceptor.com">https://topapi.free.beeceptor.com</a></code> to send post request</p>
<p>You can verify if the requests are being made here: <code><a href="https://beeceptor.com/console/topapi">https://beeceptor.com/console/topapi</a></code></p>
<mark>The JavaScript API/feature which is used here is - <a href="https://developer.mozilla.org/en-US/docs/Web/API/Beacon_API">Beacon API</a>, which helps to send AJAX requests even after the page is unloaded</mark>
<br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br>
<script type="text/javascript">
// This code is Vanilla JS, you can equivalently use jQuery
// $(document).ready() or $(window).on()
let timeSpentScrolling = 0;
let isHalted = false;
let haltedStartTime, haltedEndTime;
let totalHaltedTime = 0;
const update_halt_state = () => {
if (isHalted) {
isHalted = false;
haltedEndTime = new Date().getTime()
totalHaltedTime += (haltedEndTime - haltedStartTime) / 1000
} else {
isHalted = true;
haltedStartTime = new Date().getTime()
}
}
// Listen for scroll events
window.addEventListener('scroll', () => {
timeSpentScrolling += 1.8;
update_halt_state()
});
document.addEventListener("DOMContentLoaded", () => {
const start = new Date().getTime();
// AVERAGE SCROLLING INTERVAL - 39 seconds
setInterval(() => {
if (new Date().getTime() - start > 39000) {
update_halt_state()
}
}, 39000)
window.addEventListener("beforeunload", () => {
const end = new Date().getTime();
update_halt_state()
const totalTime = ((end - start) / 1000) - (timeSpentScrolling / 1000) - totalHaltedTime
navigator.sendBeacon("https://topapi.free.beeceptor.com", totalTime)
});
});
</script>
</body>
</html>