How to Target based on whether a Cookie Value Exists

UPDATE 2019: We now have native “Storage” box rules in our conditions editor for targeting if a Cookie exists or target based on Cookie values. Of course, you can write custom JS for advanced use cases, but checking the presence or contents of cookies to trigger boxes is now possible in the UI.

Let’s say you want to target based on whether a Cookie value exists. This is good if you want to target new vs. existing customers and you already drop a cookie on them. In this example, we assume that for all existing customers, there is a cookie called “ExistingCustomer”.

Here is what the Custom JS would look like (it goes in the Custom JS Parent Section under After Document Ready):

//get Cookie
function getCookie(name) 
{
  var value = "; " + document.cookie;
  var parts = value.split("; " + name + "=");
  if (parts.length == 2) return parts.pop().split(";").shift();
}

//set Rule
function setRule(value)
{
  var Rule = document.createElement("div");
  Rule.setAttribute("id",value);
  Rule.setAttribute("style","display:none");
  document.body.appendChild(Rule);
}

if( getCookie("ExistingCustomer") )
{
  setRule("digioh-ExistingCustomer");
}
Once you place this in your Custom JS section, it’s time to set up a rule. To target an existing user you would use our HTML jQuery Exists Rule and it would look like this:

HTML Exists jQuery Contains #digioh-ExistingCustomer

Now, lets say you wanted to target customers who don’t have that cookie value. This is what your rule would look like:

HTML Exists jQuery DOES NOT CONTAIN #digioh-ExistingCustomer

If you need help setting up cookie-based targeting, send us an email, and we’ll be glad to help!