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", {});
});
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
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", {});
}
})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With