[英]How to Detect if Cookies Are Disabled on Microsoft Edge / Windows 10?
我有一些适用于所有其他浏览器的代码,但不适用于Windows 10 / Microsoft Edge。 有任何想法吗?
function areCookiesEnabled() { // Quick test if browser has cookieEnabled host property if (navigator.cookieEnabled) { return true; } // Create cookie document.cookie = "cookietest=1"; var ret = document.cookie.indexOf("cookietest=") !== -1; // Delete cookie document.cookie = "cookietest=1; expires=Thu, 01-Jan-1970 00:00:01 GMT"; return ret; } if (areCookiesEnabled()) { alert("Cookies are enabled!"); } else { alert("Cookies are not enabled!"); }
Cookie在设置中被阻止
堆栈溢出表示已启用Cookie
你可以创建一个cookie并对其进行测试我有一个小,但非常有用的库在这里通过这个,你可以做这样的事情
if(navigator.cookieEnabled||cookier.make("test","test",1))
//if one of these returns true {
if(cookier.parse("test))
//if test cookie is set
{
console.log("cookies are allowed");
}
}
我最终找到了一个cookie库,通过实际创建一个真正的cookie来测试它的正确方法:
https://github.com/ScottHamper/Cookies
使用的方法是Cookies.enabled
。 这是作者使用的代码部分:
var testKey = 'cookies.js';
var areEnabled = Cookies.set(testKey, 1).get(testKey) === '1';
Cookies.expire(testKey);
return areEnabled;
我在Win10 / Edge开发工具中进行了尝试,它对我有用。
如果您不想包含单独的js,则可以如下更新功能
function areCookiesEnabled() {
var cookieEnabled = navigator.cookieEnabled;
// When cookieEnabled flag is present and false then cookies are disabled.
if (cookieEnabled === false) {
return false;
}
var isIE = /*@cc_on!@*/false;
var isEdge = !isIE && !!window.StyleMedia;
// try to set a test cookie if we can't see any cookies and we're using
// either a browser that doesn't support navigator.cookieEnabled
// or IE / Edge (which always returns true for navigator.cookieEnabled)
if ((cookieEnabled === null || isIE || isEdge)) {
document.cookie = "testcookie=1";
if (GetCookieValue("testcookie") != "1") {
return false;
} else {
document.cookie = "testcookie=; expires=" + new Date(0).toUTCString();
}
}
return true;
}
// Get cookie value by passing the key.
function GetCookieValue(strKey) {
// split cookies by '; ', keep space as it is.
var arrCookies = document.cookie.split('; ');
for (var i = 0; i < arrCookies.length; i++) {
var keyValuePair = GetKeyValuePair(arrCookies[i]);
// Match the key.
if (keyValuePair.key === strKey) {
// return value of matched key.
return keyValuePair.value;
}
}
// Return an empty string if key is not present.
return "";
}
// Get key value pair from the cookie string.
function GetKeyValuePair(strCookie) {
// "=" is a valid character in a cookie value according to RFC6265, so cannot `split('=')`
var separatorIndex = strCookie.indexOf('=');
// IE omits the "=" when the cookie value is an empty string
separatorIndex = separatorIndex < 0 ? strCookie.length : separatorIndex;
var key = strCookie.substr(0, separatorIndex);
var decodedKey;
try {
decodedKey = decodeURIComponent(key);
} catch (e) {
}
return {
key: decodedKey,
value: strCookie.substr(separatorIndex + 1)
};
};
我已经通过这种方式解决了这个问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.