简体   繁体   English

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

[英]Detect if cookies are enabled in the browser

The code below works in all current browser except for IE. 下面的代码在IE以外的所有当前浏览器中均可使用。 In IE the message doesn't display. 在IE中不会显示该消息。

  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? 有人可以告诉我如何使上述代码在IE 10和11中工作吗?

I've tried code that works in IE but then it works in most browser except for Safari. 我试过了在IE中可以使用的代码,但随后它在除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. 但这对于FF,Safari和Chrome仍然显示。 So then I have two messages displaying.... 因此,我将显示两条消息。

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 JavaScript中的“ $(document).ready()”

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM