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

前端 未结 9 1198
鱼传尺愫
鱼传尺愫 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 15:17

    This JavaScript function has always worked for me:

    if (typeof areCookiesAllowed !== 'function')
        {
            function areCookiesAllowed()
                {
                    var cookies_allowed = navigator.cookieEnabled;
    
                    if (!cookies_allowed)
                        {
                            try
                                {
                                    var cur_dt = new Date();
                                    var cur_tm = cur_dt.getTime();
    
                                    document.cookie = 'cookie_test_' + cur_tm + '=1';
                                    cookies_allowed = document.cookie.indexOf('cookie_test_' + cur_tm + '=') !== -1;
                                    document.cookie = 'cookie_test_' + cur_tm + '=1; expires=Thu, 01-Jan-1970 00:00:01 GMT';
                                }
                            catch(err)
                                {
                                    return false;
                                };
                        };
    
                    return cookies_allowed;
                };
        };
    

    if (typeof areCookiesAllowed !== 'function')
    	{
    		function areCookiesAllowed()
    			{
    				var cookies_allowed = navigator.cookieEnabled;
    
    				if (!cookies_allowed)
    					{
    						try
    							{
    								var cur_dt = new Date();
    								var cur_tm = cur_dt.getTime();
    
    								document.cookie = 'cookie_test_' + cur_tm + '=1';
    								cookies_allowed = document.cookie.indexOf('cookie_test_' + cur_tm + '=') !== -1;
    								document.cookie = 'cookie_test_' + cur_tm + '=1; expires=Thu, 01-Jan-1970 00:00:01 GMT';
    							}
    						catch(err)
    							{
    								return false;
    							};
    					};
    
    				return cookies_allowed;
    			};
    	};
      
    var result_elmt = document.getElementById("result");
    var result;
    
    if (areCookiesAllowed() === true)
    	{
    		result = 'Congratulations! Cookies are enabled in this Web Browser and on this website!';
    	}
    else
    	{
    		result = 'Aww Snap! Unfortunatly cookies are NOT enabled in this Web Browser or are disabled on this website.';
    	};
    
    result_elmt.innerHTML = result;
    alert(result);

提交回复
热议问题