Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails: Javascript for tracking sessions firing inconsistently

I have some JS code in my Rails app that fires a tracking event to Mixpanel on a new session.

Theoretically, before any other event is fired, I should see the "New Session" event first. But on some visits, I don't see the "New Session" event which means it's not being fired on some occasions.

What's wrong with the below code?

$(function(){
  var currentLocation = window.location.hostname;
  var lastLocation = document.referrer;
  if (lastLocation.indexOf(currentLocation) > -1) {
  } else {
    mixpanel.track("New Session", {});
  }
  mixpanel.track("Page View", {});
});
like image 554
Jackson Cunningham Avatar asked Jul 04 '16 16:07

Jackson Cunningham


2 Answers

If you're using Turbolinks the ready event is not fired after the first page load, so you need to bind to custom turbolinks events like page:load like:

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

like image 89
neydroid Avatar answered Oct 20 '22 17:10

neydroid


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

We know the code is being ran, I'd recommend utilizing the if-statement for your tracking and adding 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", {});
  }
})
like image 25
Blair Anderson Avatar answered Oct 20 '22 17:10

Blair Anderson