๐คท What does it do?
This custom JavaScript variable calculates the time a user has spent on a given page. This is done by recording the time when a page is first loaded, then recording the time again when the user navigates away from the page or closes the window. The difference between these two times is the time spent on the page.
๐งโ๐ป Usecase
The ‘Time Spent on Page’ can provide insights into user engagement. By knowing how long a user stays on a particular page, you can understand if they are finding the content on the page useful or engaging. For example, if users consistently spend a lot of time on a certain page, it may indicate that the content is valuable to them. Conversely, if users often leave a page very quickly, it could indicate that they are not finding what they are looking for.
๐ Instructions
To implement this, you would need to use the Session Storage or Local Storage of the web browser. This example uses Session Storage:
function() {
// Check if 'start time' exists in Session Storage
if (sessionStorage.getItem('start_time')) {
// Get the current time
var end_time = new Date().getTime();
// Retrieve the start time from Session Storage
var start_time = sessionStorage.getItem('start_time');
// Calculate the time spent on page in seconds
var time_spent = (end_time - start_time) / 1000;
// Clear the start time from Session Storage
sessionStorage.removeItem('start_time');
// Return the time spent on page
return time_spent;
} else {
// If 'start time' doesn't exist in Session Storage, create it
var start_time = new Date().getTime();
sessionStorage.setItem('start_time', start_time);
// Return null since the user has just loaded the page
return null;
}
}
This JavaScript function works by storing the time that the user first loads the page in Session Storage. When the user navigates away from the page, the function calculates the difference between the current time and the stored start time, giving the time spent on the page. If there is no start time in Session Storage (i.e., if the user has just loaded the page), the function creates one and returns null.
Note that this function needs to be triggered twice – once when the page loads and once when the user navigates away. You could create a Page View trigger for the page load, and a History Change or Page Unload trigger for when the user leaves the page. Also, be aware that the Session Storage is cleared when the user closes the browser, so this method might not accurately track time spent across multiple browsing sessions.
Isn’t this the macro you were looking for? Check-out all the macro’s which I’ve shared on my site or request one.