forked from MarkBiesheuvel/optimizely-custom-code
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
211bf13
commit 8eda8b7
Showing
1 changed file
with
27 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,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 | ||
} | ||
}); | ||
} | ||
}); |