开发者

How to find out if a cookie is already there?

开发者 https://www.devze.com 2023-01-27 21:00 出处:网络
So I do simple JS function like function writ开发者_C百科eCookie() { var the_cookie = \"users_resolution=\"+ screen.width +\"x\"+ screen.height;

So I do simple JS function like

function writ开发者_C百科eCookie() 
{ 

var the_cookie = "users_resolution="+ screen.width +"x"+ screen.height; 

document.cookie=the_cookie 

} 

how tm make sure that users_resolution is set?


You could write a function like so:

  function getCookie(cName) {
    var cVal = document.cookie.match('(?:^|;) ?' + cName + '=([^;]*)(?:;|$)');
    if (!cVal) {
      return "";
    } else {
      return cVal[1];
    }
  }

Then, after you have set the cookie, you can call getCookie() and test it's return value, if it's equal to an empty string, or "", which is false, then the cookie doesn't exist. Otherwise you've got a valid cookie value.

The above paragraph in code:

var cookie = getCookie("users_resolution");
if (!cookie) {
   // cookie doesn't exist
} else {
  // cookie exists
}


If you just do

var cookies = document.cookie;

then the string cookies will contain a semicolon-separated list of cookie name-value pairs. You can split the string on ";" and loop through the results, checking for the presence of your cookie name.


I know you didn't tag this as jQuery, but I made a jQuery plugin to handle cookies, and this is the snippet that reads the cookie value:

  /**
   * RegExp Breakdown:
   * search from the beginning or last semicolon: (^|;)
   * skip variable number of spaces (escape backslash in string): \\s*
   * find the name of the cookie: name
   * skip spaces around equals sign: \\s*=\\s*
   * select all non-semicolon characters: ([^;]*)
   * select next semicolon or end of string: (;|$)
   */
  var regex = new RegExp( '(^|;)\\s*'+name+'\\s*=\\s*([^;]*)(;|$)' );
  var m = document.cookie.match( regex );
  // if there was a match, match[2] is the value
  // otherwise the cookie is null ?undefined?
  val =  m ? m[2] : null;


You might want to use indexOf to check whether it exists or not:

if(document.cookie.indexOf('users_resolution=') > 0){
  // cookie was set
}
0

精彩评论

暂无评论...
验证码 换一张
取 消