检测浏览器中是否启用了cookie [英] Detect if cookies are enabled in the browser

查看:111
本文介绍了检测浏览器中是否启用了cookie的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面的代码在IE以外的所有当前浏览器中均有效。在IE中,该消息不会显示。

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.");
    } 

有人可以告诉我我该怎么做才能使上述代码在IE中起作用10和11?

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

我尝试了可在IE中使用的代码,但随后它可在除Safari之外的大多数浏览器中使用。这是代码。

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>

但这对于FF,Safari和Chrome仍然显示。因此,我将显示两个消息。...

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

推荐答案

这可以做到:

$(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 "";
}

JavaScript中的 $(document).ready()

这篇关于检测浏览器中是否启用了cookie的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆