Skip to content

Instantly share code, notes, and snippets.

@MatthewDaniels
Created March 16, 2016 21:52
Show Gist options
  • Save MatthewDaniels/3867c9995c24c84e27d8 to your computer and use it in GitHub Desktop.
Save MatthewDaniels/3867c9995c24c84e27d8 to your computer and use it in GitHub Desktop.
Load a user's IP address via a service so we can add it to a dataLayer in GTM - beware we do not want to store it in it's raw form, but we can manipulate the data in GTM once there (ie: check against a filtered list and add a flag)
var request = new XMLHttpRequest();
// if the endpoint changes, then manipulation of the returned data may need to change in the onReadyState handler
request.open('GET', 'https://api.ipify.org', true);
request.onreadystatechange = function() {
if (this.readyState === 4) {
if (this.status >= 200 && this.status < 400) {
// Success!
var data = this.responseText;
console.log('respose', data);
//setup the dataLayer if it has not already been setup
window.dataLayer = window.dataLayer ? window.dataLayer : [];
// add the ip to the datalayer, firing an ipGathered Event at the same time.
dataLayer.push({
'event' : 'ipGathered',
'ip' : data
});
} else {
// Error :(
// we could fire this into GTM too to track failures.
}
}
};
request.send();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment