如何仅在浏览器中禁用 cookie 时显示消息? [英] How to show a message only if cookies are disabled in browser?

查看:22
本文介绍了如何仅在浏览器中禁用 cookie 时显示消息?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何仅在浏览器中禁用 cookie 时显示消息?像 http://stackoverflow.com 显示 JavaScript 是否被禁用.

How to show a message only if cookies are disabled in browser? like http://stackoverflow.com show if JavaScript is disabled.

推荐答案

曾经有一个 JavaScript navigator.cookieEnabled 接口,但今天的浏览器有一个更多的范围cookie 控制不仅仅是启用"/禁用",包括会话/持久选项、第一方/第三方、特定于站点的设置和 P3P.所以现在嗅探这个属性没什么用.

There used to be a JavaScript navigator.cookieEnabled interface, but today browsers have a much wider range of cookie controls than just ‘enabled’/‘disabled’, including session/persistent options, first-party/third-party, site-specific settings and P3P. So sniffing this property is of little use now.

不,确定您是否可以设置 cookie 的唯一可靠方法是尝试设置它,看看它是否仍然存在.另一个问题是,当用户的隐私控制不允许时,许多浏览器会将持久性 cookie 降级为会话 cookie,但 IE 不会.

No, the only reliable way to find out whether you can set a cookie is to try to set it, and see if it's still there. Another wrinkle is that whilst many browsers will downgrade a persistent cookie to a session cookie when the user's privacy controls don't allow them, IE will not.

如果您尝试在 IE 中设置持久性 cookie 当它们被禁用时,cookie 将被简单地扔在地板上.如果您使用简单的会话 cookie 检查器,发现 cookie 已启用,然后尝试设置持久性 cookie,这可能会发现您.并且您无法摆脱尝试设置为会话 cookie 持久性 cookie,因为当您在禁用持久性 cookie 的情况下在 IE 中设置持久性 cookie 时,它​​甚至会删除em> 现有的同名会话 cookie.哦,IE!

If you try to set a persistent cookie in IE when they are disabled, the cookie will simply be thrown on the floor. This can catch you out if you use a simple session-cookie checker, find cookies are enabled, and then try to set a persistent cookie. And you can't get away with trying to set as a session cookie and a persistent cookie, because when you set a persistent cookie in IE with persistent cookies disabled, it will even delete the existing session cookie of the same name. Oh IE!

因此,如果您需要设置一个持久性 cookie 但在持久性不可用的情况下使用会话,您必须首先使用它来找出您可以做什么:

So if you need to set a persistent cookie but make do with session where persistent isn't available, you'd have to use this first to find out what you're allowed to do:

// Find out what cookies are supported. Returns:
// null - no cookies
// false - only session cookies are allowed
// true - session cookies and persistent cookies are allowed
// (though the persistent cookies might not actually be persistent, if the user has set
// them to expire on browser exit)
//
function getCookieSupport() {
    var persist= true;
    do {
        var c= 'gCStest='+Math.floor(Math.random()*100000000);
        document.cookie= persist? c+';expires=Tue, 01-Jan-2030 00:00:00 GMT' : c;
        if (document.cookie.indexOf(c)!==-1) {
            document.cookie= c+';expires=Sat, 01-Jan-2000 00:00:00 GMT';
            return persist;
        }
    } while (!(persist= !persist));
    return null;
}

这篇关于如何仅在浏览器中禁用 cookie 时显示消息?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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