How to detect that JavaScript and/or Cookies are disabled?

前端 未结 9 1204
鱼传尺愫
鱼传尺愫 2020-11-27 14:13

How to detect that JavaScript or Cookies are disabled in the user\'s browser and notify him any help ?

9条回答
  •  隐瞒了意图╮
    2020-11-27 14:59

    Assuming JavaScript is enabled, this will tell you if cookies are enabled or not. Works in old browsers.

    // returns 1 or 0 instead of true or false. Returns null if inconclusive.
    function cookiesEnabled() {
        var i, j, cookies, found;
        if (navigator.cookieEnabled===false) return 0;
        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.
    }
    

    To display a message only when JavaScript is disabled use

    
    

提交回复
热议问题