Javascript navigator.cookieEnabled Browser Compatibility

前端 未结 4 684
北荒
北荒 2020-12-08 08:40

How well supported is navigator.cookieEnabled? Can I safely rely on it for all browsers?

4条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-08 08:51

    navigator.cookieEnabled is not always reliable and does not work at all on old browsers.

    This answer will work on all browsers that support JavaScript. Additionally this does not need jQuery and it deletes the test cookie after the test is complete.

    // returns 1 or 0 instead of true or false. Returns null if inconclusive.
    function cookiesEnabled() {
        var i, j, cookies, found;
        document.cookie = 'testcookiesenabled=1';
        for (i=0; i<2; i++) {
            found = false;
            cookies = document.cookie.split(';');
            j = cookies.length;
            while(j--) {
                while (cookies[j].charAt(0)==' ') {// trim spaces
                    cookies[j] = cookies[j].substring(1);
                }
                if (cookies[j].indexOf('testcookiesenabled=')==0) {
                    found = true;
                    break;
                }
            }
            if (!found) {
                return i;
            }
            // Delete test cookie.
            document.cookie = 'testcookiesenabled=; expires=Thu, 01 Jan 1970 00:00:01 GMT';
        }
        // Results inconclusive.
    }
    

提交回复
热议问题