Below are a few examples of cookies with a custom expiration. The code snippets can be placed within a (non-preloader) Javascript Code extension.  In other cases, the Persist Data Values extension is recommended.

Set Session cookie 

This code snippet will create a cookie that will be removed at the end of the user's session.

document.cookie = "COOKIE_NAME=" + 'COOKIE_VALUE' + ";path=/;domain=" + utag.cfg.domain + ";expires=";
b['cp.COOKIE_NAME'] = 'COOKIE_VALUE'; // this updates the Tealium data object on the page

Set Visitor cookie (expires after n years)

This code snippet will create a cookie that will expire after n number of years.

document.cookie 
= "COOKIE_NAME=" + 'COOKIE_VALUE' + ";path=/;domain=" + utag.cfg.domain + ";expires=Thu, 31 Dec [insert Year, example 2034] 00:00:00 GMT"; b['cp.COOKIE_NAME'] = 'COOKIE_VALUE'; 

Set hours cookie

This code snippet will create a cookie that will expire after a number of hours.

document.cookie = "COOKIE_NAME=" + 'COOKIE_VALUE' + ";path=/;domain=" + utag.cfg.domain + ";expires=" + (function() {
 var d = new Date();
 d.setTime(d.getTime() + (NUM_HOURS_HERE * 3600000));
 return d.toGMTString()
})() + "";
b['cp.COOKIE_NAME'] = 'COOKIE_VALUE';

Set days cookie

This code snippet will create a cookie that will expire after a number of days.

document.cookie = "COOKIE_NAME=" + 'COOKIE_VALUE' + ";path=/;domain=" + utag.cfg.domain + ";expires=" + (function() {
 var d = new Date();
 d.setTime(d.getTime() + (NUM_DAYS_HERE * 86400000));
 return d.toGMTString()
})() + ""; b['cp.COOKIE_NAME'] = 'COOKIE_VALUE'; function displayCookies() { var fname = getCookie("firstname"); if (fname == null ) { fname = ""; } if (fname != "") { fname = "firstname=" + fname; } var lname = getCookie("lastname"); if (lname == null ) { lname = ""; } if (lname != "") { lname = "lastname=" + lname; } alert(fname + " " + lname); }
function getCookie(name) { var nameEQ = name + "="; //alert(document.cookie); var ca = document.cookie.split(';'); for (var i = 0; i < ca.length; i++) { var c = ca[i]; while (c.charAt(0) == ' ') c = c.substring(1); if (c.indexOf(nameEQ) != -1) return c.substring(nameEQ.length, c.length); } return null ; }

 

Version history
Revision #:
9 of 9
Last update:
a month ago
Updated by: