Skip to content

Commit

Permalink
Add the option to regenerate the page view ID with each page view eve…
Browse files Browse the repository at this point in the history
…nt (close #436)
  • Loading branch information
chuwy committed Nov 2, 2016
1 parent 38f97e4 commit 87224f2
Show file tree
Hide file tree
Showing 5 changed files with 74 additions and 12 deletions.
3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,10 @@
"name": "snowplow-tracker",
"version": "2.7.0",
"devDependencies": {
"js-base64": "2.1.9",
"JSON": "1.0.0",
"browser-cookie-lite": "0.3.1",
"grunt": "1.0.0",
"grunt": "0.4.5",
"grunt-browserify": "5.0.0",
"grunt-contrib-concat": "0.5.1",
"grunt-lodash": "0.3.0",
Expand Down
3 changes: 2 additions & 1 deletion src/js/snowplow.js
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,7 @@
/* Tracker identifier with version */
version = 'js-' + '<%= pkg.version %>', // Update banner.js too

// Initial ID. Can be regenerated by trackPageView
pageViewId = uuid.v4(),

/* Contains four variables that are shared with tracker.js and must be passed by reference */
Expand Down Expand Up @@ -127,7 +128,7 @@
// Flush all POST queues
lodash.forEach(mutSnowplowState.bufferFlushers, function (flusher) {
flusher();
})
});

/*
* Delay/pause (blocks UI)
Expand Down
35 changes: 29 additions & 6 deletions src/js/tracker.js
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,8 @@
* @param functionName global function name
* @param namespace The namespace of the tracker object
* @param version The current version of the JavaScript Tracker
* @param pageViewId ID for the current page view, to be attached to all events in the web_page context
* @param pageViewId Initial (can be modified) ID for the current page view, to be attached to
* all events in the web_page context.
* @param mutSnowplowState An object containing hasLoaded, registeredOnLoadHandlers, and expireDateTime
* Passed in by reference in case they are altered by snowplow.js
* @param argmap Optional dictionary of configuration options. Supported fields and their default values:
Expand Down Expand Up @@ -264,16 +265,15 @@
commonContexts = [],

// Enhanced Ecommerce Contexts to be added on every `trackEnhancedEcommerceAction` call
enhancedEcommerceContexts = [];
enhancedEcommerceContexts = [],

// Whether pageViewId should be regenerated after each trackPageView. Affect web_page context
preservePageViewId = false;

if (argmap.hasOwnProperty('discoverRootDomain') && argmap.discoverRootDomain) {
configCookieDomain = helpers.findRootDomain();
}

if (autoContexts.webPage) {
commonContexts.push(getWebPageContext());
}

if (autoContexts.gaCookies) {
commonContexts.push(getGaCookiesContext());
}
Expand Down Expand Up @@ -738,6 +738,16 @@
return ('https:' === documentAlias.location.protocol ? 'https' : 'http') + '://' + rawUrl;
}

/**
* Reset initial `pageViewId` if necessary after successful
* `trackPageView`
*/
function resetPageViewState() {
if (!preservePageViewId) {
pageViewId = uuid.v4();
}
}

/**
* Add common contexts to every event
* TODO: move this functionality into the core
Expand All @@ -748,6 +758,10 @@
function addCommonContexts(userContexts) {
var combinedContexts = commonContexts.concat(userContexts || []);

if (autoContexts.webPage) {
combinedContexts.push(getWebPageContext());
}

// Add PerformanceTiming Context
if (autoContexts.performanceTiming) {
var performanceTimingContext = getPerformanceTimingContext();
Expand Down Expand Up @@ -1160,6 +1174,8 @@
pageTitle,
purify(customReferrer || configReferrerUrl),
addCommonContexts(finalizeContexts(context, contextCallback)));

resetPageViewState();

// Send ping (to log that user has stayed on page)
var now = new Date();
Expand Down Expand Up @@ -2177,6 +2193,13 @@
trackError: function (message, filename, lineno, colno, error, contexts) {
var enrichedContexts = addCommonContexts(contexts);
errorManager.trackError(message, filename, lineno, colno, error, enrichedContexts);
},

/**
* Stop regenerating `pageViewId` (available from `web_page` context)
*/
preservePageViewId: function () {
preservePageViewId = true
}
};
};
Expand Down
36 changes: 33 additions & 3 deletions tests/integration/integration.js
Original file line number Diff line number Diff line change
Expand Up @@ -37,8 +37,10 @@ define([
'intern/chai!assert',
'intern/dojo/node!lodash',
'intern/dojo/node!http',
'intern/dojo/node!url'
], function(registerSuite, assert, lodash, http, url) {
'intern/dojo/node!url',
"intern/dojo/node!js-base64"
], function(registerSuite, assert, lodash, http, url, jsBase64) {
var decodeBase64 = jsBase64.Base64.fromBase64;

/**
* Expected amount of request for each browser
Expand All @@ -47,6 +49,24 @@ define([
*/
var log = [];

function pageViewsHaveDifferentIds () {
var pageViews = lodash.filter(log, function (logLine) {
return logLine['e'] === 'pv'
});
var contexts = lodash.map(pageViews, function (logLine) {
var data = JSON.parse(decodeBase64(logLine['cx'])).data;
var wpContext = lodash.find(data, function (context) {
return context.schema === 'iglu:com.snowplowanalytics.snowplow/web_page/jsonschema/1-0-0'
});
return wpContext;
});
var ids = lodash.map(contexts, function (wpContext) {
return wpContext.data.id;
});

return lodash.uniq(ids).length >= 2;
}

function checkExistenceOfExpectedQuerystring(expected) {
function compare(e, other) { // e === expected
var result = lodash.map(e, function (v, k) {
Expand Down Expand Up @@ -100,7 +120,12 @@ define([
aid: 'CFe23a',
uid: 'Malcolm',
page: 'My Title',
cx: 'eyJzY2hlbWEiOiJpZ2x1OmNvbS5zbm93cGxvd2FuYWx5dGljcy5zbm93cGxvdy9jb250ZXh0cy9qc29uc2NoZW1hLzEtMC0xIiwiZGF0YSI6W3sic2NoZW1hIjoiaWdsdTpjb20uZXhhbXBsZV9jb21wYW55L3VzZXIvanNvbnNjaGVtYS8yLTAtMCIsImRhdGEiOnsidXNlclR5cGUiOiJ0ZXN0ZXIifX1dfQ'
cx: function (cx) {
var contexts = JSON.parse(decodeBase64(cx)).data;
return lodash.contains(contexts,
{schema:"iglu:com.example_company/user/jsonschema/2-0-0",data:{userType:'tester'}}
)
}
}), 'A page view should be detected');
},

Expand Down Expand Up @@ -163,6 +188,11 @@ define([
return true
}
}))
},

'Check pageViewId is regenerated for each trackPageView': function () {
assert.isTrue(pageViewsHaveDifferentIds())
}

})
});
9 changes: 8 additions & 1 deletion tests/pages/integration-template.html
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,10 @@
window.snowplow('newTracker', 'cf', subdomain + '.ngrok.io', {
encodeBase64: true,
appId: 'CFe23a',
platform: 'mob'
platform: 'mob',
contexts: {
webPage: true
}
});

window.snowplow('setUserId', 'Malcolm');
Expand All @@ -37,6 +40,9 @@
}
]);

// This should have different pageViewId in web_page context
window.snowplow('trackPageView');

window.snowplow('trackStructEvent', 'Mixes', 'Play', 'MRC/fabric-0503-mix', '', '0.0');
window.snowplow('trackUnstructEvent', {
schema: 'iglu:com.acme_company/viewed_product/jsonschema/5-0-0',
Expand Down Expand Up @@ -74,6 +80,7 @@
// trackTrans sends the transaction to Snowplow tracking servers.
// Must be called last to commit the transaction.
window.snowplow('trackTrans');

</script>

</body>
Expand Down

0 comments on commit 87224f2

Please sign in to comment.