I have two domains - domain1.com, domain2.com. When user open domain1 js script does cors request to domain2.com and it return simple string response. When js script receives a response it set cookie COOKIE_NAME = response text. When I analyze the access log of domain1 than I have only 40% percent of sessions where cookie COOKIE_NAME set.
Any ideas why cookie not set in 60% percent of the sessions?
This code does not support IE, because IE users are <1% part of our users. Code:
var DONE = (typeof XMLHttpRequest.DONE !== 'undefined') ? XMLHttpRequest.DONE : 4;
document.addEventListener('DOMContentLoaded', updateCookie);
function updateCookie() {
var value = getCookie(COOKIE_NAME);
if (typeof value !== 'undefined') {
return;
}
var xhr = new XMLHttpRequest();
try {
xhr.open('GET', DOMAIN2, true);
xhr.withCredentials = true;
xhr.onreadystatechange = function () {
if (xhr.readyState !== DONE) {
return;
}
if (xhr.status === 200) {
var value = xhr.responseText;
setCookie(COOKIE_NAME, value, COOKIE_LIFE_TIME);
}
};
xhr.send();
}
function getCookie(name) {
var matches = document.cookie.match(new RegExp(
"(?:^|; )" + name.replace(/([.$?*|{}()\[\]\\\/+^])/g, '\\$1') + "=([^;]*)"
));
return matches ? decodeURIComponent(matches[1]) : undefined;
}
function setCookie(name, value, expires) {
if (typeof expires === "number" && expires) {
var date = new Date();
date.setTime(date.getTime() + expires * 1000);
expires = date;
}
if (expires && expires.toUTCString) {
expires = expires.toUTCString();
}
value = encodeURIComponent(value);
var updatedCookie = name + "=" + value;
updatedCookie += "; path=/; " + "expires=" + expires;
document.cookie = updatedCookie;
}