Javascript navigator.cookieEnabled浏览器兼容性

dtb*_*rne 18 javascript cookies

支持得有多好navigator.cookieEnabled?我可以安全地依赖所有浏览器吗?

And*_*y E 33

我知道它至少存在于IE 6及更高版本,Firefox 1及更高版本,并且Dottoro报告它受到所有主流浏览器的支持.然而,它不是任何DOM规范的一部分,因此不能保证在可用的或正确实现由所有的浏览器(例如,具有有限DOM实现移动浏览器).

正如一些人所发现的那样,navigator.cookieEnabled即使当前网站阻止了cookie ,IE 也会返回true .这意味着你现在根本不能依赖这个属性,你应该完全避免它.

对于完整的跨浏览器cookie支持检查,您可能希望使用以下内容:

var cookies = ("cookie" in document && (document.cookie.length > 0 ||
        (document.cookie = "test").indexOf.call(document.cookie, "test") > -1));
Run Code Online (Sandbox Code Playgroud)

演示:http://codetester.org/31011785

这将false在禁用cookie或不支持DOM级别2属性的浏览器中返回document.cookie,这在JS中是可以的.


mik*_*son 23

在刚才的快速测试中(使用IE9),当浏览器阻止该站点的cookie时,navigator.cookieEnabled似乎仍然返回true.

换句话说,Cookie已启用,但不适用于您所在的特定页面.

因此,您需要在设置cookie时测试cookie是否真正有效.应该是正确的代码(修改自Andy E的答案):

var cookies = 
    ("cookie" in document && (document.cookie.length > 0 ||
    (document.cookie = "test").indexOf.call(document.cookie, "test") > -1))
Run Code Online (Sandbox Code Playgroud)

检查navigator.cookieEnabled确实没有意义.

  • +1.这是真的.如果您没有阅读其他内容,请阅读:"检查navigator.cookieEnabled确实没有意义." (4认同)