Assign Country from Browser/IP Address to Attribute

❗️

Third-Party Usage

GEO-IP lookup is a third-party platform for geolocation, use at your own risk.

When you use a native integration with Drift, these attributes are automatically collected for you- all you have to do is map them in their configuration page. If you're using a non-natively integrated CRM or MAP, you probably still want to know where your users are located. But what do you do when your system is non-native or more custom? How on earth will you know where Carmen Sandiego is when she reaches out to you? Hold onto your hats, we know what to do.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script> <!--jQuery Google CDN -->

drift.on('ready', function(){
  $.getJSON('https://geolocation-db.com/json/', function(data) {
      var c_code = data.country_code;
      var c_name = data.country_name;
      drift.api.setUserAttributes({
        custom_country_code: c_code,
        custom_country: c_name
      });
  });
});
drift.on('ready', function(){
	let request = new XMLHttpRequest();
	request.open('GET', 'https://geolocation-db.com/json/', true);
	request.onload = function() {
    if (this.status >= 200 && this.status < 400) {
      // Success!
      let data = JSON.parse(this.response);
      drift.api.setUserAttributes({
        custom_country_code: data.country_code,
        custom_country: data.country_name
      });
    }
	};
	request.send();
});

In this example, we're using a bit of jQuery or JavaScript to grab the country name and code from the browser. Then, we set them to custom attributes called custom_country_code and custom_country. You can set as many custom attributes as you like, and name them whatever you wish. Make sure to get all attributes required for a complete lead or contact record creation. Use whichever version of the code fits your site best!

For customers implementing this tag through Google Tag Manager, the 'let' declaration is not supported, so this implementation will be preferred as it uses the 'var' declaration

<script>
drift.on('ready', function(){
    var request = new XMLHttpRequest();
    request.open('GET', 'https://geolocation-db.com/json/', true);
    request.onload = function() {
    if (this.status >= 200 && this.status < 400) {
      // Success!
      var data = JSON.parse(this.response);
      drift.api.setUserAttributes({
        custom_country_code: data.country_code,
        custom_country: data.country_name
      });
    }
    };
    request.send();
});
</script>

As always, your custom code should be added to your Drift snippet, not replacing it.