PowerUser
PowerUser

Reputation: 812

JavaScript: detect if cookies are disabled and redirect to an error page

So if cookies are disabled execute document.location = /enable-cookies.aspx. I have this code so far:

var cookiesEnabled = navigator.cookieEnabled;

And what should I do next? Maybe write a cookie and check if it's value is sent? Or should I just use an if() statement?

if (cookiesEnabled){ // or something like this

}

Then at last redirect to the file "/enable-cookies.aspx" if cookies are disabled.

Upvotes: 0

Views: 489

Answers (1)

user3188159
user3188159

Reputation:

Add the following JavaScript code inside your <head></head> tag:

<script type="text/javascript">
    function detect()
    {
        if (navigator.cookieEnabled)
        {
            // Do something else, maybe?
        }
        else
        {
           document.location = '/enable-cookies.aspx';
        }
    }
</script>

And then add the following JavaScript event in your <body></body> tag:

<body onload="detect();"><!-- ...Some HTML code... --></body>

Upvotes: 2

Related Questions