Detect if cookies are enabled in the browser

2019-09-09 12:57发布

问题:

The code below works in all current browser except for IE. In IE the message doesn't display.

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

Can someone tell me what I can do to make the above code work in IE 10 & 11?

I've tried code that works in IE but then it works in most browser except for Safari. Here's the code.

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

But this still displays for FF, Safari, and Chrome. So then I have two messages displaying....

回答1:

This will do it:

$(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