Rails: Javascript for session tracking, shooting inconsistently

I have JS code in my Rails application that fires a tracking event in Mixpanel in a new session.

Theoretically, before any other event is fired, I must first see the "New Session" event. But in some visits I do not see the "New Session" event, which means that it does not start in some cases.

What is wrong with the code below?

$(function(){ var currentLocation = window.location.hostname; var lastLocation = document.referrer; if (lastLocation.indexOf(currentLocation) > -1) { } else { mixpanel.track("New Session", {}); } mixpanel.track("Page View", {}); }); 
+5
source share
2 answers

If you use Turbolinks, the ready event does not fire after loading the first page, so you need to bind to custom turbolinks events, for example page:load , for example:

 var ready; ready = function() { var currentLocation = window.location.hostname; var lastLocation = document.referrer; if (lastLocation.indexOf(currentLocation) > -1) { } else { mixpanel.track("New Session", {}); } mixpanel.track("Page View", {}); }; $(document).ready(ready); $(document).on('page:load', ready); 

For Rails 5, the event name changed to turbolinks:load

+4
source

You need to figure out how to reproduce the problem before you can solve the problem.

We know that the code is running, I would recommend using an if-statement to track and add data.

 $(function(){ var currentLocation = window.location.hostname; var lastLocation = document.referrer; if (lastLocation.indexOf(currentLocation) > -1) { // internal links mixpanel.track("Page View", {}); } else { // external or non-existant link // bookmarks and email links won't have referrers mixpanel.track("New Session", {referrer: document.referrer}); mixpanel.track("Page View", {}); } }) 
+1
source

All Articles