检测浏览器中是否启用了cookie

时间:2016-06-15 00:44:39

标签: javascript internet-explorer cookies

以下代码适用于IE以外的所有当前浏览器。在IE中,消息不显示。

  if (navigator.cookieEnabled == 0) {
    document.write("Cookies are not enabled.");
    } 

有人可以告诉我我可以做些什么来使上述代码在IE 10& 11?

我已经尝试过在IE中运行的代码,但它可以在除Safari之外的大多数浏览器中运行。这是代码。

   <script type="text/javascript">
    if(/MSIE \d|Trident.*rv:/.test(navigator.userAgent))
        var cookies = ("cookie" in document && (document.cookie.length > 0 ||
        (document.cookie = "test").indexOf.call(document.cookie, "test") > -1));
    document.write(cookies ? "" : "Cookies are not enabled.");
</script>

但这仍然适用于FF,Safari和Chrome。那么我有两条消息显示....

1 个答案:

答案 0 :(得分:0)

这样做:

$(document).ready(function () {
 var event = window.attachEvent || window.addEventListener;
 if (!trySetCookie()) {
  // cookies are disabled
 }
 else{
 // cookies are enabled
 }
}
function trySetCookie() {
 setCookie("testCookie", "testValue", 1);
 var cookieValue = getCookie("testCookie");
 if (cookieValue == "" || cookieValue == null)
    return false;
 return true;
}
// set a test cookie in the user's browser
function setCookie(cname, cvalue, exdays) {
 var d = new Date();
 d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000));
 var expires = "expires=" + d.toGMTString();
 document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
}
// read the test cookie
function getCookie(cname) {
 var name = cname + "=";
 var decodedCookie = decodeURIComponent(document.cookie);
 var ca = decodedCookie.split(';');
 for (var i = 0; i < ca.length; i++) {
    var c = ca[i];
    while (c.charAt(0) == ' ') {
        c = c.substring(1);
    }
    if (c.indexOf(name) == 0) {
        return c.substring(name.length, c.length);
    }
 }
 return "";
}

"$(document).ready()" in JavaScript