Hi there Stack Overflow users. I have created a nice little script to append A/B testing information from their API to one of our session cookies to be stored in our database. This script is working in all browsers but IE (surprise surprise!). This is the code:
<script>
function addTParam() {
function getCookie(acqsource) {
var i, x, y, ARRcookies = document.cookie.split(';');
for (i = 0; i < ARRcookies.length; i++) {
x = ARRcookies[i].substr(0, ARRcookies[i].indexOf('='));
y = ARRcookies[i].substr(ARRcookies[i].indexOf('=') + 1);
x = x.replace(/^\s+|\s+$/g, '');
if (x == acqsource) {
return unescape(y);
}
}
}
if (typeof (abtester) != 'undefined') {
var experimentId = 0;
var variationId = 0;
var variationIdx = -1;
var activeExpts = abtester.activeExperiments;
var values;
var newArray = [];
for (var i = 0; i < activeExpts.length; i++) {
experimentId = activeExpts[i];
if (abtester.variationIdsMap.hasOwnProperty(experimentId)) {
variationId = abtester.variationIdsMap[experimentId];
newArray = newArray.concat(variationId);
}
}
newArray = activeExpts.concat(newArray);
values = newArray.join('-');
var contents = getCookie('acqsource');
if (values && values.length > 0 && (contents.indexOf(values) === -1)) {
contents += "&tp=" + values;
document.cookie = "acqsource=" + contents + "; domain=domain.com; path=/";
}
}
}
$(document).ready(function () {
addTParam();
});
</script>
To give a bit of an explanation, this function will append a string of “tp=123456-7890123” to the acqsource cookie. However, when it goes to execute the getCookie function, IE either: a) cannot find it, or b) is saying it doesnt exist (which it should, the page creates that cookie on load). This is all being loaded after the DOM is finished, so that isn’t the issue.
I’ve googled this issue exhaustively, and even approached a couple of other devs in my company, and all of us are stumped. Thanks in advance!
So, I have figured this out. The way that I was checking for the cookies was to check if there was an
=. This was the issue, as the way that IE sets session cookies, if the cookie is null, it comes back as undefined as there is no=in that cookie. So a bit of code magic got me this:Basically, you need to check if the cookie is undefined, and if not, write and append. However, if the cookie is empty, you need to just add it to it. Hope this can help anyone who ends up in my predicament with session cookies and IE.