Fixed visit recreation on cookie timeout (#174) (#189)

Eugene Shuvalov committed Jun 24, 2016
commit 819d50fd7750c2ca86b9690e2cd74d170b90be7d
Showing 1 changed file with 53 additions and 46 deletions
vendor/assets/javascripts/ahoy.js +53 -46
@@ @@ -98,6 +98,10 @@
}
function trackEvent(event) {
+ if (!ahoy.getVisitId()) {
+ ready(createVisit)
+ }
+
ready( function () {
// ensure JSON is defined
if (canStringify) {
@@ @@ -138,63 +142,64 @@
}
// main
-
- visitId = getCookie("ahoy_visit");
- visitorId = getCookie("ahoy_visitor");
- track = getCookie("ahoy_track");
-
- if (visitId && visitorId && !track) {
- // TODO keep visit alive?
- log("Active visit");
- setReady();
- } else {
- if (track) {
- destroyCookie("ahoy_track");
- }
-
- if (!visitId) {
- visitId = generateId();
- setCookie("ahoy_visit", visitId, visitTtl);
- }
-
- // make sure cookies are enabled
- if (getCookie("ahoy_visit")) {
- log("Visit started");
-
- if (!visitorId) {
- visitorId = generateId();
- setCookie("ahoy_visitor", visitorId, visitorTtl);
+ function createVisit() {
+ visitId = ahoy.getVisitId();
+ visitorId = ahoy.getVisitorId();
+ track = getCookie("ahoy_track");
+
+ if (visitId && visitorId && !track) {
+ // TODO keep visit alive?
+ log("Active visit");
+ setReady();
+ } else {
+ if (track) {
+ destroyCookie("ahoy_track");
}
- var data = {
- visit_token: visitId,
- visitor_token: visitorId,
- platform: ahoy.platform || "Web",
- landing_page: window.location.href,
- screen_width: window.screen.width,
- screen_height: window.screen.height
- };
-
- // referrer
- if (document.referrer.length > 0) {
- data.referrer = document.referrer;
+ if (!visitId) {
+ visitId = generateId();
+ setCookie("ahoy_visit", visitId, visitTtl);
}
- log(data);
-
- $.post(visitsUrl, data, setReady, "json");
- } else {
- log("Cookies disabled");
- setReady();
+ // make sure cookies are enabled
+ if (getCookie("ahoy_visit")) {
+ log("Visit started");
+
+ if (!visitorId) {
+ visitorId = generateId();
+ setCookie("ahoy_visitor", visitorId, visitorTtl);
+ }
+
+ var data = {
+ visit_token: visitId,
+ visitor_token: visitorId,
+ platform: ahoy.platform || "Web",
+ landing_page: window.location.href,
+ screen_width: window.screen.width,
+ screen_height: window.screen.height
+ };
+
+ // referrer
+ if (document.referrer.length > 0) {
+ data.referrer = document.referrer;
+ }
+
+ log(data);
+
+ $.post(visitsUrl, data, setReady, "json");
+ } else {
+ log("Cookies disabled");
+ setReady();
+ }
}
}
ahoy.getVisitId = ahoy.getVisitToken = function () {
- return visitId;
+ return getCookie("ahoy_visit");
};
ahoy.getVisitorId = ahoy.getVisitorToken = function () {
- return visitorId;
+ return getCookie("ahoy_visitor");
};
ahoy.reset = function () {
@@ @@ -273,6 +278,8 @@
ahoy.trackChanges();
};
+ createVisit();
+
// push events from queue
try {
eventQueue = JSON.parse(getCookie("ahoy_events") || "[]");