Created
January 30, 2015 16:12
-
-
Save rlucha/6ddba81e6814eb58be71 to your computer and use it in GitHub Desktop.
Intercom init & event tracking
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function UserTrackingSrv(ids) { | |
var self = this; | |
var appIDs = ids; | |
var userID; | |
var userLogged = false; | |
var ic; | |
this.init = function() { | |
if (appIDs.analyticsID !== undefined) { | |
window.GoogleAnalyticsObject = 'ga'; | |
window.ga = window.ga || function(){ | |
(window.ga.q = window.ga.q || []).push(arguments); | |
}; | |
window.ga.l =1 * new Date(); | |
var a = document.createElement('script'); | |
var m = document.getElementsByTagName('script')[0]; | |
a.async = 1; | |
a.src = '//www.google-analytics.com/analytics.js'; | |
m.parentNode.insertBefore(a, m); | |
//testing | |
ga('create', appIDs.analyticsID, {'cookieDomain': 'none'}); | |
} | |
if (appIDs.intercomID !== undefined) { | |
var w = window; | |
var icc = w.Intercom; | |
if (typeof icc === "function") { | |
icc('reattach_activator'); | |
icc('update'); | |
} else { | |
var d = document; | |
var i = function() { | |
i.c(arguments); | |
}; | |
i.q = []; | |
i.c = function(args) { | |
i.q.push(args); | |
}; | |
w.Intercom = i; | |
var l = function() { | |
var s = d.createElement('script'); | |
s.type = 'text/javascript'; | |
s.async = true; | |
s.src = 'https://widget.intercom.io/widget/'+ appIDs.intercomID; | |
var x = d.getElementsByTagName('script')[0]; | |
x.parentNode.insertBefore(s, x); | |
}; | |
if (w.attachEvent) { | |
w.attachEvent('onload', l); | |
} else { | |
w.addEventListener('load', l, false); | |
} | |
} | |
ic = window.Intercom; | |
} | |
}; | |
this.setUser = function(userId, email) { | |
userLogged = true; | |
ga('create', appIDs.analyticsID, { 'name': 'userLogged', 'userId': userId }); | |
window.Intercom('boot', { | |
app_id: appIDs.intercomID, | |
email: email, | |
user_id: userId | |
}); | |
self.sendEvent({ | |
name: 'logged-in', | |
user_id: userId, | |
metadata: { | |
label: 'test' | |
} | |
}); | |
}; | |
this.sendEvent = function(e) { | |
var epoch = new Date().getTime(); | |
if (userLogged) { | |
ga('userLogged.send', 'event', 'userTracking', e.name, e.metadata.label); | |
ic('trackEvent', e.name , epoch); | |
} else { | |
ga('send', 'event', 'userTracking', e.name, e.metadata.label); | |
} | |
}; | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment