If a cookie does not exist, alerts and redirects

I need to check if a cookie exists when the user lands on the page, and if the cookie does not exist, I need a pop-up warning and then redirect to another page.

+5
source share
3 answers
if( $.cookie('cookiename') == null ) { 
    alert("OH NOES U NO HAS COOKIE");
    window.location.replace('http://url');
}
+8
source
if( document.cookie.indexOf("cookiename=") < 0) {
    alert("Cookie not found, redirecting you.");
    location.href = "newpage.html";
}

Be careful not to use a cookie name, which may be the end of another cookie name. If possible, you will need to read the full cookie or use PHP instead.

+7
source

Usage Javascript ReadCookie()Function

ReadCookie(), you immediately understand it is used to read a cookie.

You can read any cookies if they are read in the same domain on which they were installed.

<script type="text/javascript" language="JavaScript">
var acookie = ReadCookie("cookiename");
if(acookie.length == 0)
 { 
  //redirect somewhere 
 }
</script>
+1
source

All Articles