Skip to content

Commit

Permalink
Add time-on-page custom event
Browse files Browse the repository at this point in the history
  • Loading branch information
MarkBiesheuvel committed Apr 20, 2023
1 parent 211bf13 commit 8eda8b7
Showing 1 changed file with 27 additions and 0 deletions.
27 changes: 27 additions & 0 deletions shared-code/time-on-page.js
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
}
});
}
});

0 comments on commit 8eda8b7

Please sign in to comment.