0
我有兩個域 - domain1.com,domain2.com。當用戶打開domain1時,js腳本將cors請求發送到domain2.com,並返回簡單的字符串響應。當js腳本收到響應時,它會設置cookie COOKIE_NAME =響應文本。當我分析domain1的訪問日誌時,我只有cookie COOKIE_NAME設置的會話的40%。JS CORS:它允許設置cookie值= cors請求的響應嗎?
任何想法爲什麼cookie沒有在60%的會話中設置?
此代碼不支持IE,因爲IE用戶是< 1%的用戶。 代碼:
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;
}