【问题标题】:JS CORS: Is it allowed to set cookie value = response of cors request?JS CORS:是否允许设置 cookie 值 = cors 请求的响应?
【发布时间】:2020-03-20 07:22:24
【问题描述】:

我有两个域 - domain1.com、domain2.com。当用户打开 domain1 js 脚本向 domain2.com 发出 cors 请求时,它返回简单的字符串响应。当 js 脚本收到响应时,它会设置 cookie COOKIE_NAME = 响应文本。当我分析 domain1 的访问日志时,我只有 40% 的会话设置了 cookie COOKIE_NAME。

知道为什么 60% 的会话中没有设置 cookie 吗?

此代码不支持 IE,因为 IE 用户占我们用户的

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

【问题讨论】:

    标签: javascript cookies cross-domain


    【解决方案1】:

    经过研究,我发现问题有几个原因:

    • 在访问日志中计算唯一 cookie 的过程不正确。访问日志需要清除“thrash”日志条目,例如 API 请求、静态资源请求等。
    • 使用广告拦截器的用户(约占所有用户的 15%)。因为请求的域在阻止列表中
    • 禁用 3d 方 cookie 的用户
    • 机器人
    • 使用 IE 的用户

    【讨论】:

      猜你喜欢
      • 2016-07-21
      • 2012-04-26
      • 2019-07-19
      • 2023-03-10
      • 2018-07-28
      • 1970-01-01
      • 2023-03-14
      • 2021-02-09
      • 1970-01-01
      相关资源
      最近更新 更多