Retrieve Cookie Values and Pass to Drift

Overview

When Drift's JavaScript snippet has been successfully installed to your website, contact attributes are automatically collected from the browser, Drift Intel providers, as well as throughout playbook bot-flows and live conversations with Drift users.

Sometimes, there are custom values about the website visitor that are set as Browser Cookies by systems not natively integrated to Drift, where these values would be useful to pass into Drift to help target playbooks, personalize bot flows, power conversation-routing, and ultimately sync downstream to Marketing Automation or CRM once the conversation closes.

Documenting Cookies

Modern web-browsers support the document.cookie function which returns an array of all the current cookie values:

1477

This array needs to be split and cleaned-up in order to be useful to Drift. By installing this JavaScript snippet to your site, the getCookie function will be available to be invoked once Drift has finished initializing the widget_bootstrap, which prepares the JavaScript API to consume data about the website visitor.

function getCookie(name) {
    var cookieArr = document.cookie.split(";");
    for(var i = 0; i < cookieArr.length; i++) {
        var cookiePair = cookieArr[i].split("=");
        if(name == cookiePair[0].trim()) {
            return decodeURIComponent(cookiePair[1]);
        }
    }
    return null;
}

Once Drift is Loaded

In order to capture the value of a specific cookie, in this example a cookie named "IsoCode" reflecting a 2-digit country code value set by the website, we need to use the drift.on('ready') wrapper to ensure that the JavaScript API is fully initialized.

Inside of that wrapper, we will invoke the getCookie() function that was declared on page load, retrieving in this case the value "US" for visitors in the United States as a variable using the var declaration.

Finally, this JavaScript passes that customCountry variable into Drift as a Custom Contact Attribute, in this case named "isoCountryCode".

drift.on('ready',function(){
  var customCountry = getCookie('IsoCode');
  drift.api.setUserAttributes({
    isoCountryCode: customCountry
  });
})

This example shows a simple console.log(); function to illustrate the ability for this JavaScript to capture the visitor's cookie-value for IsoCountry:

956

Checking For Success

Once you have implemented all of the appropriate JavaScript and completed a test-conversation in the browser, you can go into your Contacts within Drift and filter by Contact Attributes to ensure the expected cookie-value is now saved on the profile for that website visitor.

2124

What's Next?

Now that you're capturing custom Cookie values and passing them into Drift, check out other ways to set data attributes using Javascript!