forked from MarkBiesheuvel/optimizely-custom-code
-
Notifications
You must be signed in to change notification settings - Fork 0
/
time-on-page.js
27 lines (23 loc) · 840 Bytes
/
time-on-page.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
// NOTE: This implementation does not consider whether the page is in an active tab of the browser.
// If you want to exclude time where the current tab is not active you can use the visibilitychange event to pause the timer.
// TODO: Replace the value below with a unique event key for this experiment.
// For example, 'checkout_time_on_page'.
const eventName = 'example_time_on_page';
// Capture the starting time
const startDate = new Date();
// Attach event listener
window.addEventListener('beforeunload', () => {
const endDate = new Date();
const spentTime = (endDate.getTime() - startDate.getTime()) / 1000;
// Verify that Optimizely is on the page
if (window.optimizely) {
// Send event
window.optimizely.push({
type: 'event',
eventName,
tags: {
value: spentTime
}
});
}
});