jQuery check if Cookie exists, if not create it

2019-01-17 06:16发布

I cannot get this code to work I must be missing something pretty simple. I am trying to check to see if a Cookie exists, if it does {do nothing} if it doesn't {create it}. I am testing the cookie by including an alert on a page. Basically I do not want the cookie to keep re-creating with a referral url, I am trying to grab only the FIRST referred URL.

$(document).ready(function(){   
  if ($.cookie('bas_referral') == null ){
   var ref = document.referrer.toLowerCase();  
   // set cookie  
   var cookURL =  $.cookie('bas_referral', ref, { expires: 1 }); 
  } 
 });  

Displaying the current cookie contents:

    // get cookie  
    alert($.cookie('bas_referral'));  

    // delete cookie  
     $.cookie('bas_referral', null);

5条回答
叛逆
2楼-- · 2019-01-17 06:46

I think the bulletproof way is:

if (typeof $.cookie('token') === 'undefined'){
 //no cookie
} else {
 //have cookie
}

Checking the type of a null, empty or undefined var always returns 'undefined'

Edit: You can get there even easier:

if (!!$.cookie('token')) {
 // have cookie
} else {
 // no cookie
}

!! will turn the falsy values to false. Bear in mind that this will turn 0 to false!

查看更多
The star\"
3楼-- · 2019-01-17 06:51

I was having alot of trouble with this because I was using:

if($.cookie('token') === null || $.cookie('token') === "")
{
      //no cookie
}
else
{
     //have cookie
}

The above was ALWAYS returning false, no matter what I did in terms of setting the cookie or not. From my tests it seems that the object is therefore undefined before it's set so adding the following to my code fixed it.

if($.cookie('token') === null || $.cookie('token') === "" 
    || $.(cookie('token') === "null" || $.cookie('token') === undefined)
{
      //no cookie
}
else
{
     //have cookie
}
查看更多
Bombasti
4楼-- · 2019-01-17 07:02

Try this very simple:

            var cookieExist = $.cookie("status");
            if(cookieExist == "null" ){
                alert("Cookie Is Null");

            }
查看更多
▲ chillily
5楼-- · 2019-01-17 07:04

You can set the cookie after having checked if it exists with a value.

 $(document).ready(function(){            
      if ($.cookie('cookie')) { //if cookie isset
         //do stuff here like hide a popup when cookie isset
         //document.getElementById("hideElement").style.display = "none";
      }else{
         var CookieSet = $.cookie('cookie', 'value'); //set cookie
      }       
 });
查看更多
你好瞎i
6楼-- · 2019-01-17 07:05
 $(document).ready(function() {

     var CookieSet = $.cookie('cookietitle', 'yourvalue');

     if (CookieSet == null) {
          // Do Nothing
     }
     if (jQuery.cookie('cookietitle')) {
          // Reactions
     }
 });
查看更多
登录 后发表回答