0
votes

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;
}
1

1 Answers

0
votes

After research, i got that there are several reasons for a problem:

  • A not correct procedure of counting unique cookies in an access log. Access log needs to be cleared of 'thrash' log entries, such as API requests, requests for static resources, etc.
  • Users with ad blocker (~15% of all users). Because requested domain is in the block list
  • Users with disabled 3d party cookies
  • Bots
  • Users with IE