Created
July 19, 2020 14:12
-
-
Save ak--47/2dac48e56f3ee44502cb6a42e00c0821 to your computer and use it in GitHub Desktop.
Mixpanel .track() with no dependencies
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
//a vanilla implementation of .track() | |
//docs: https://developer.mixpanel.com/docs/http | |
//by AK | |
function trackStuff(uuid, eventName, props, token) { | |
//the mixpanel data model | |
let spec = { | |
"event": eventName, | |
"properties": { | |
// these two properties are required! | |
"distinct_id": uuid, | |
"token": token | |
} | |
}; | |
//iterate through props | |
if (props) { | |
for (prop in props) { | |
//append them to our spec | |
spec.properties[prop] = props[prop]; | |
} | |
} | |
// base64 encode | |
let payload = btoa(JSON.stringify(spec)); | |
//make a vanilla HTTP request as per: https://developer.mixpanel.com/docs/http#section-tracking-events | |
let xhttp = new XMLHttpRequest(); | |
xhttp.onreadystatechange = function() { | |
if (this.readyState === 4 && this.status === 200) { | |
console.log("data sent"); | |
} | |
}; | |
xhttp.open("GET", "https://api.mixpanel.com/track/?data=" + payload + "&ip=1", true); | |
xhttp.send(); | |
} | |
// how we might use this | |
let someProps = { | |
"user type": "maverick", | |
"interests": ["foo", "bar", "baz", "qux"] | |
}; | |
trackStuff("ak!", "App Open", someProps, "009c696fd3f040f5b32297ac50845210"); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment