Last active
June 9, 2019 17:40
-
-
Save steven-miller/878a9105f1525e280214dae3ca86fbf1 to your computer and use it in GitHub Desktop.
Time-based page view tracker in HubSpot - can be added as a custom module and then can filter on custom events
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
<script> | |
$(document).ready(function() { | |
// verbose: get current unix datetime - outputs in MS | |
var dateNow = Date.now(); | |
// if the "cookie" already exists | |
if (localStorage.getItem('viewCounter') !== null) { | |
// shorthand for viewCounter | |
var viewCounter = JSON.parse(localStorage.getItem('viewCounter')); | |
// clean out any old view dates | |
// 86400000 == milliseconds in a day | |
var countLastThirty = viewCounter.filter(function(timestamp) { | |
return (dateNow - timestamp) < {{ module.date_range_to_track * 86400000 }}; // check how many days between | |
}); | |
// add current datetime to end of countLastThirty | |
countLastThirty.push(dateNow); | |
// check full length of array - are we over threshhold? | |
while (countLastThirty.length > {{ module.page_views_in_date_range }}) { | |
countLastThirty.shift(); | |
} | |
// at 10 items that are within 30 days - time to fire event | |
if (countLastThirty.length === {{ module.page_views_in_date_range }}) { | |
// fire event | |
_hsq.push(["trackEvent", { id: `Viewed {{ module.page_views_in_date_range }} pages in {{ module.date_range_to_track }} days` }]); | |
} | |
localStorage.setItem('viewCounter', JSON.stringify(countLastThirty)); | |
} else { | |
localStorage.setItem('viewCounter', JSON.stringify([dateNow])); | |
} | |
}); | |
</script> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment