如何检查用户是否接受cookie

时间:2011-10-17 07:54:44

标签: javascript yui yahoo

使用java脚本,如何检查用户是否接受域的cookie。 YUI是否有任何此类组件需要检查?

1 个答案:

答案 0 :(得分:0)

<强>库:

<script type="text/javascript">
    function createCookie(name, value, days) {
        var expires;
        if (days) {
            var date = new Date();
            date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
            expires = "; expires=" + date.toGMTString();
        }
        else expires = "";
        document.cookie = name + "=" + value + expires + "; path=/";
    }

    function readCookie(name) {
        var nameEQ = name + "=";
        var ca = document.cookie.split(';');
        for (var i = 0; i < ca.length; i++) {
            var c = ca[i];
            while (c.charAt(0) == ' ') c = c.substring(1, c.length);
            if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
        }
        return null;
    }

    function eraseCookie(name) {
        createCookie(name, "", -1);
    }

    function areCookiesEnabled() {
        var r = false;
        createCookie("testing", "Hello", 1);
        if (readCookie("testing") != null) {
            r = true;
            eraseCookie("testing");
        }
        return r;
    }
</script>

要运行的代码:

<script type="text/javascript">
    alert(areCookiesEnabled());
</script>

<强>记住:

仅在允许运行Javascript时才有效!

<强>信用卡:

这是here的重新发布。原作者是balexandre