Skip to content

Instantly share code, notes, and snippets.

@steven-miller
Last active June 9, 2019 17:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save steven-miller/878a9105f1525e280214dae3ca86fbf1 to your computer and use it in GitHub Desktop.
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
<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