Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
44 changes: 43 additions & 1 deletion amplitude.js
Original file line number Diff line number Diff line change
Expand Up @@ -157,13 +157,16 @@ Amplitude.prototype._eventId = 0;
Amplitude.prototype._sending = false;
Amplitude.prototype._lastEventTime = null;
Amplitude.prototype._sessionId = null;
Amplitude.prototype._newSession = false;

/**
* Initializes Amplitude.
* apiKey The API Key for your app
* opt_userId An identifier for this user
* opt_config Configuration options
* - saveEvents (boolean) Whether to save events to local storage. Defaults to true.
* - utmParams (string) Optional utm data in query string format.
* Pulled from location.search otherwise.
*/
Amplitude.prototype.init = function(apiKey, opt_userId, opt_config) {
try {
Expand Down Expand Up @@ -211,11 +214,16 @@ Amplitude.prototype.init = function(apiKey, opt_userId, opt_config) {
this.sendEvents();
}

// Parse the utm properties out of cookies and query for adding to user properties.
var utmParams = opt_config && opt_config.utmParams || location.search;
this._utmProperties = Amplitude._getUtmData(Cookie.get('__utmz'), utmParams);

this._lastEventTime = parseInt(localStorage.getItem(LocalStorageKeys.LAST_EVENT_TIME)) || null;
this._sessionId = parseInt(localStorage.getItem(LocalStorageKeys.SESSION_ID)) || null;
this._eventId = localStorage.getItem(LocalStorageKeys.LAST_EVENT_ID) || 0;
var now = new Date().getTime();
if (!this._sessionId || !this._lastEventTime || now - this._lastEventTime > this.options.sessionTimeout) {
this._newSession = true;
this._sessionId = now;
localStorage.setItem(LocalStorageKeys.SESSION_ID, this._sessionId);
}
Expand All @@ -226,6 +234,10 @@ Amplitude.prototype.init = function(apiKey, opt_userId, opt_config) {
}
};

Amplitude.prototype.isNewSession = function() {
return this._newSession;
};

Amplitude.prototype.nextEventId = function() {
this._eventId++;
return this._eventId;
Expand Down Expand Up @@ -254,6 +266,31 @@ var _saveCookieData = function(scope) {
});
};

Amplitude._getUtmParam = function(name, query) {
name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
var regex = new RegExp("[\\?&]" + name + "=([^&#]*)");
var results = regex.exec(query);
return results === null ? undefined : decodeURIComponent(results[1].replace(/\+/g, " "));
};

Amplitude._getUtmData = function(rawCookie, query) {
// Translate the utmz cookie format into url query string format.
var cookie = rawCookie ? '?' + rawCookie.split('.').slice(-1)[0].replace(/\|/g, '&') : '';

var fetchParam = function (queryName, query, cookieName, cookie) {
return Amplitude._getUtmParam(queryName, query) ||
Amplitude._getUtmParam(cookieName, cookie);
};

return {
utm_source: fetchParam('utm_source', query, 'utmcsr', cookie),
utm_medium: fetchParam('utm_medium', query, 'utmcmd', cookie),
utm_campaign: fetchParam('utm_campaign', query, 'utmccn', cookie),
utm_term: fetchParam('utm_term', query, 'utmctr', cookie),
utm_content: fetchParam('utm_content', query, 'utmcct', cookie),
};
};

Amplitude.prototype.saveEvents = function() {
try {
localStorage.setItem(this.options.unsentKey, JSON.stringify(this._unsentEvents));
Expand Down Expand Up @@ -336,6 +373,11 @@ Amplitude.prototype.logEvent = function(eventType, eventProperties) {
localStorage.setItem(LocalStorageKeys.LAST_EVENT_TIME, this._lastEventTime);
localStorage.setItem(LocalStorageKeys.LAST_EVENT_ID, eventId);

// Add the utm properties, if any, onto the user properties.
var userProperties = {};
object.merge(userProperties, this.options.userProperties || {}, this._utmProperties);
object.merge(userProperties, this._utmProperties);
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is this line necessary?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, the but the 3rd param on the previous line should be removed. object.merge only merges 2 params at a time.


eventProperties = eventProperties || {};
var event = {
device_id: this.options.deviceId,
Expand All @@ -351,7 +393,7 @@ Amplitude.prototype.logEvent = function(eventType, eventProperties) {
device_model: ua.os.family,
language: this.options.language,
event_properties: eventProperties,
user_properties: this.options.userProperties || {},
user_properties: userProperties,
uuid: UUID(),
library: {
name: 'amplitude-js',
Expand Down
4 changes: 2 additions & 2 deletions amplitude.min.js

Large diffs are not rendered by default.

38 changes: 37 additions & 1 deletion src/amplitude.js
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,8 @@ Amplitude.prototype._newSession = false;
* opt_userId An identifier for this user
* opt_config Configuration options
* - saveEvents (boolean) Whether to save events to local storage. Defaults to true.
* - utmParams (string) Optional utm data in query string format.
* Pulled from location.search otherwise.
*/
Amplitude.prototype.init = function(apiKey, opt_userId, opt_config) {
try {
Expand Down Expand Up @@ -102,6 +104,10 @@ Amplitude.prototype.init = function(apiKey, opt_userId, opt_config) {
this.sendEvents();
}

// Parse the utm properties out of cookies and query for adding to user properties.
var utmParams = opt_config && opt_config.utmParams || location.search;
this._utmProperties = Amplitude._getUtmData(Cookie.get('__utmz'), utmParams);

this._lastEventTime = parseInt(localStorage.getItem(LocalStorageKeys.LAST_EVENT_TIME)) || null;
this._sessionId = parseInt(localStorage.getItem(LocalStorageKeys.SESSION_ID)) || null;
this._eventId = localStorage.getItem(LocalStorageKeys.LAST_EVENT_ID) || 0;
Expand Down Expand Up @@ -150,6 +156,31 @@ var _saveCookieData = function(scope) {
});
};

Amplitude._getUtmParam = function(name, query) {
name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
var regex = new RegExp("[\\?&]" + name + "=([^&#]*)");
var results = regex.exec(query);
return results === null ? undefined : decodeURIComponent(results[1].replace(/\+/g, " "));
};

Amplitude._getUtmData = function(rawCookie, query) {
// Translate the utmz cookie format into url query string format.
var cookie = rawCookie ? '?' + rawCookie.split('.').slice(-1)[0].replace(/\|/g, '&') : '';

var fetchParam = function (queryName, query, cookieName, cookie) {
return Amplitude._getUtmParam(queryName, query) ||
Amplitude._getUtmParam(cookieName, cookie);
};

return {
utm_source: fetchParam('utm_source', query, 'utmcsr', cookie),
utm_medium: fetchParam('utm_medium', query, 'utmcmd', cookie),
utm_campaign: fetchParam('utm_campaign', query, 'utmccn', cookie),
utm_term: fetchParam('utm_term', query, 'utmctr', cookie),
utm_content: fetchParam('utm_content', query, 'utmcct', cookie),
};
};

Amplitude.prototype.saveEvents = function() {
try {
localStorage.setItem(this.options.unsentKey, JSON.stringify(this._unsentEvents));
Expand Down Expand Up @@ -232,6 +263,11 @@ Amplitude.prototype.logEvent = function(eventType, eventProperties) {
localStorage.setItem(LocalStorageKeys.LAST_EVENT_TIME, this._lastEventTime);
localStorage.setItem(LocalStorageKeys.LAST_EVENT_ID, eventId);

// Add the utm properties, if any, onto the user properties.
var userProperties = {};
object.merge(userProperties, this.options.userProperties || {});
object.merge(userProperties, this._utmProperties);

eventProperties = eventProperties || {};
var event = {
device_id: this.options.deviceId,
Expand All @@ -247,7 +283,7 @@ Amplitude.prototype.logEvent = function(eventType, eventProperties) {
device_model: ua.os.family,
language: this.options.language,
event_properties: eventProperties,
user_properties: this.options.userProperties || {},
user_properties: userProperties,
uuid: UUID(),
library: {
name: 'amplitude-js',
Expand Down
75 changes: 75 additions & 0 deletions test/amplitude.js
Original file line number Diff line number Diff line change
Expand Up @@ -187,6 +187,81 @@ describe('Amplitude', function() {
});
});

describe('gatherUtm', function() {
beforeEach(function() {
amplitude.init(apiKey);
});

afterEach(function() {
reset();
});

it('should add utm params to the user properties', function() {
cookie.set('__utmz', '133232535.1424926227.1.1.utmcct=top&utmccn=new');

reset();
amplitude.init(apiKey, undefined, {
utmParams: '?utm_source=amplitude&utm_medium=email&utm_term=terms'
});

amplitude.setUserProperties({user_prop: true});
amplitude.logEvent('UTM Test Event', {});

assert.lengthOf(server.requests, 1);
var events = JSON.parse(querystring.parse(server.requests[0].requestBody).e);
assert.deepEqual(events[0].user_properties, {
user_prop: true,
utm_campaign: 'new',
utm_content: 'top',
utm_medium: 'email',
utm_source: 'amplitude',
utm_term: 'terms'
});

});

it('should get utm params from the query string', function() {
var query = '?utm_source=amplitude&utm_medium=email&utm_term=terms' +
'&utm_content=top&utm_campaign=new';
var utms = Amplitude._getUtmData('', query);
assert.deepEqual(utms, {
utm_campaign: 'new',
utm_content: 'top',
utm_medium: 'email',
utm_source: 'amplitude',
utm_term: 'terms'
});
});

it('should get utm params from the cookie string', function() {
var cookie = '133232535.1424926227.1.1.utmcsr=google|utmccn=(organic)' +
'|utmcmd=organic|utmctr=(none)|utmcct=link';
var utms = Amplitude._getUtmData(cookie, '');
assert.deepEqual(utms, {
utm_campaign: '(organic)',
utm_content: 'link',
utm_medium: 'organic',
utm_source: 'google',
utm_term: '(none)'
});
});

it('should prefer utm params from the query string', function() {
var query = '?utm_source=amplitude&utm_medium=email&utm_term=terms' +
'&utm_content=top&utm_campaign=new';
var cookie = '133232535.1424926227.1.1.utmcsr=google|utmccn=(organic)' +
'|utmcmd=organic|utmctr=(none)|utmcct=link';
var utms = Amplitude._getUtmData(cookie, query);
assert.deepEqual(utms, {
utm_campaign: 'new',
utm_content: 'top',
utm_medium: 'email',
utm_source: 'amplitude',
utm_term: 'terms'
});
});
});

describe('sessionId', function() {

var clock;
Expand Down