开发者

Retrieve Cookie Content

I'm trying tof ind a way to retrieve the content of a cookie in javascript.

Let's assume that the cookie is named "Google"

and lets also assume content of this cookie is just "blah"

开发者_Python百科

I've been looking online and all I find are complex functions, and what I was wondering if there is a simple one line such code that retreives the value of the content in a cookie'

such as -

var myCookie = cookie.content('Google');

I don't want long parsers to check for various cookies or if the cookies have multiple value or whatever..Thanks!


QuirksMode has a very simple, but effective cookie script.

var Google = readCookie("Google"); // Google is now "blah"


Not exactly a simple one-line solution but close!

var results = document.cookie.match ( '(^|;) ?' + cookiename + '=([^;]*)(;|$)' );
if ( results ) myCookie = decodeURIComponent(results[2] ) ;


You'll have to parse the cookie jar yourself but it isn't that hard:

var name    = 'the_cookie_you_want';
var value   = null;
var cookies = document.cookie.split(/\s*;\s*/);
for(var i = 0; i < cookies.length; i++) {
    if(cookies[i].substring(0, name.length + 1) == (name + '=')) {
        value = decodeURIComponent(cookies[i].substring(name.length + 1));
        break;  
    }
}


You can use document.cookie, or document.cookie.split(';') to get a full list of key/values.


In javascript all cookies are stored in a single string. THe cookies are separated by a ; A possible function to read cookies is:

function readCookie(myCookieName)
{
  if (document.cookie.length > 0)
  {
    var start = document.cookie.indexOf(myCookieName + "=");
    if (start != -1)
    {
      start = start + myCookieName.length + 1;
      var end = document.cookie.indexOf(";",start);
      if (end == -1) end = document.cookie.length;
      return unescape(document.cookie.substring(start ,end ));
    }else{
      return "";
    }
  }
  return "";
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜