简体   繁体   English

按名称读取 javascript cookie

[英]Read a javascript cookie by name

I have set a cookie using我已经使用

document.cookie = 
    'MYBIGCOOKIE=' + value + 
    '; expires=' + now.toGMTString() + 
    '; path=/';

Now there are between 5 and 10 cookies set on this site, is there a way to check the value ofthis cookie by name.现在这个网站上设置了 5 到 10 个 cookie,有没有办法通过名称检查这个 cookie 的值。

if (document.cookie.MYBIGCOOKIE == '1') {
    alert('it is 1')
}

Use the RegExp constructor and multiple replacements to clarify the syntax:使用 RegExp 构造函数和多个替换来阐明语法:

function getCook(cookiename) 
  {
  // Get name followed by anything except a semicolon
  var cookiestring=RegExp(cookiename+"=[^;]+").exec(document.cookie);
  // Return everything after the equal sign, or an empty string if the cookie name not found
  return decodeURIComponent(!!cookiestring ? cookiestring.toString().replace(/^[^=]+./,"") : "");
  }

//Sample usage
var cookieValue = getCook('MYBIGCOOKIE');

Unfortunately, Javascript's cookie syntax is nowhere near as nice as that.不幸的是,Javascript 的 cookie 语法远没有那么好。 In fact, in my opinion, it's one of the worst designed parts.事实上,在我看来,它是设计最差的部分之一。

When you try to read document.cookie , you get a string containing all the cookies set.当您尝试读取document.cookie时,您会得到一个包含所有 cookie 集的字符串。 You have to parse the string, separating by the semicolon ;您必须解析字符串,用分号分隔; character.特点。 Rather than writing this yourself, there are plenty of versions available on the web.与其自己编写,不如在网上找到很多版本。 My favourite is the one at quirksmode.org .我最喜欢的是 quirksmode.org上的那个。 This gives you createCookie , readCookie and deleteCookie functions.这为您提供了createCookiereadCookiedeleteCookie功能。

function getCookie(c_name)
{
    var i,x,y,ARRcookies=document.cookie.split(";");

    for (i=0;i<ARRcookies.length;i++)
    {
        x=ARRcookies[i].substr(0,ARRcookies[i].indexOf("="));
        y=ARRcookies[i].substr(ARRcookies[i].indexOf("=")+1);
        x=x.replace(/^\s+|\s+$/g,"");
        if (x==c_name)
        {
            return unescape(y);
        }
     }
}

Source: W3Schools资料来源: W3Schools

Edit : as @zcrar70 noted, the above code is incorrect , please see the following answer Javascript getCookie functions编辑:正如@zcrar70 所指出的,上面的代码不正确,请看下面的答案Javascript getCookie functions

You can use the following function:您可以使用以下功能:

function getCookiesMap(cookiesString) {
  return cookiesString.split(";")
    .map(function(cookieString) {
        return cookieString.trim().split("=");
    })
    .reduce(function(acc, curr) {
        acc[curr[0]] = curr[1];
        return acc;
    }, {});
}

When, called with document.cookie as parameter, it will return an object, with the cookies keys as keys and the cookies values.当使用document.cookie作为参数调用时,它将返回一个对象,其中 cookie 键作为键,cookie 值。

var cookies = getCookiesMap(document.cookie);
var cookieValue = cookies["MYBIGCOOKIE"];

using jquery-cookie使用jquery-cookie

I find this library helpful.我觉得这个库很有帮助。 3.128 kb of pure convenience. 3.128 kb 的纯粹便利。

add script添加脚本

<script src="/path/to/jquery.cookie.js"></script>

set cookie设置饼干

$.cookie('name', 'value');

read cookie读取 cookie

$.cookie('name');

One of the shortest ways is this, however as mentioned previously it can return the wrong cookie if there's similar names (MyCookie vs AnotherMyCookie):最短的方法之一是这样,但是如前所述,如果名称相似(MyCookie vs AnotherMyCookie),它可能会返回错误的 cookie:

var regex = /MyCookie=(.[^;]*)/ig;
var match = regex.exec(document.cookie);
var value = match[1];

I use this in a chrome extension so I know the name I'm setting, and I can make sure there won't be a duplicate, more or less.我在 chrome 扩展中使用它,所以我知道我正在设置的名称,并且我可以确保不会有重复,或多或少。

document.cookie="MYBIGCOOKIE=1";

Your cookies would look like:您的 cookie 将如下所示:

"MYBIGCOOKIE=1; PHPSESSID=d76f00dvgrtea8f917f50db8c31cce9"

first of all read all cookies:首先阅读所有cookies:

var read_cookies = document.cookie;

then split all cookies with ";"然后用“;”分割所有cookie :

var split_read_cookie = read_cookies.split( ";" );

then use for loop to read each value.然后使用 for 循环读取每个值。 Into loop each value split again with "=" :"="再次进入循环每个值拆分:

for ( i = 0; i < split_read_cookie.length; i++ ){
    var value = split_read_cookie[i];
    value = value.split( "=" );
    if( value[0] == "MYBIGCOOKIE" && value[1] == "1" ){
        alert( 'it is 1' );
    }
}

The point of Stack Overflow is to provide a database of good quality answers, so I am going to reference some standard source code and an article that gives examples: Stack Overflow 的目的是提供一个高质量答案的数据库,所以我将参考一些标准源代码和一篇给出示例的文章:

http://www.codelib.net/javascript/cookies.html http://www.codelib.net/javascript/cookies.html

Note: The code is regular-expression free for greatly enhanced efficiency.注意:代码没有正则表达式,大大提高了效率。

Using the source code provided, you would use cookies like this:使用提供的源代码,您将使用如下 cookie:

makeCookie('color', 'silver');

This saves a cookie indicating that the color is silver.这会保存一个 cookie,指示颜色为银色。 The cookie would expire after the current session (as soon as the user quits the browser). cookie 将在当前会话之后过期(一旦用户退出浏览器)。

makeCookie('color', 'green', { domain: 'gardens.home.com' });

This saves the color green for gardens.home.com .这为gardens.home.com保存了绿色。

makeCookie('color', 'white', { domain: '.home.com', path: '/invoices' });
makeCookie('invoiceno', '0259876', { path: '/invoices', secure: true });

saves the color white for invoices viewed anywhere at home.com.为在 home.com 上任何地方查看的发票保存白色。 The second cookie is a secure cookie, and records an invoice number.第二个 cookie 是安全 cookie,记录发票编号。 This cookie will be sent only to pages that are viewed through secure HTTPS connections, and scripts within secure pages are the only scripts allowed to access the cookie.此 cookie 将仅发送到通过安全 HTTPS 连接查看的页面,并且安全页面中的脚本是唯一允许访问 cookie 的脚本。

One HTTP host is not allowed to store or read cookies for another HTTP host.不允许一个 HTTP 主机存储或读取另一个 HTTP 主机的 cookie。 Thus, a cookie domain must be stored with at least two periods.因此,cookie 域必须存储至少两个句点。 By default, the domain is the same as the domain of the web address which created the cookie.默认情况下,域与创建 cookie 的网址的域相同。

The path of an HTTP cookie restricts it to certain files on the HTTP host. HTTP cookie 的路径将其限制为 HTTP 主机上的某些文件。 Some browsers use a default path of / , so the cookie will be available on the whole host.一些浏览器使用默认路径/ ,因此 cookie 将在整个主机上可用。 Other browsers use the whole filename.其他浏览器使用整个文件名。 In this case, if /invoices/overdue.cgi creates a cookie, only /invoices/overdue.cgi is going to get the cookie back.在这种情况下,如果/invoices/overdue.cgi创建了 cookie,则只有/invoices/overdue.cgi会取回 cookie。

When setting paths and other parameters, they are usually based on data obtained from variables like location.href, etc. These strings are already escaped, so when the cookie is created, the cookie function does not escape these values again.在设置路径和其他参数时,通常基于从 location.href 等变量获取的数据。这些字符串已经被转义,因此在创建 cookie 时,cookie 函数不会再次对这些值进行转义。 Only the name and value of the cookie are escaped, so we can conveniently use arbitrary names or values.只有 cookie 的名称和值被转义,因此我们可以方便地使用任意名称或值。 Some browsers limit the total size of a cookie, or the total number of cookies which one domain is allowed to keep.某些浏览器会限制 cookie 的总大小,或允许一个域保留的 cookie 总数。

makeCookie('rememberemail', 'yes', { expires: 7 });
makeCookie('rememberlogin', 'yes', { expires: 1 });
makeCookie('allowentergrades', 'yes', { expires: 1/24 });

these cookies would remember the user's email for 7 days, the user's login for 1 day, and allow the user to enter grades without a password for 1 hour (a twenty-fourth of a day).这些 cookie 会记住用户的电子邮件 7 天,用户的登录信息 1 天,并允许用户在 1 小时(一天的 24 分之一)内无需密码即可输入成绩。 These time limits are obeyed even if they quit the browser, and even if they don't quit the browser.即使他们退出浏览器,即使他们不退出浏览器,也会遵守这些时间限制。 Users are free to use a different browser program, or to delete cookies.用户可以自由使用不同的浏览器程序,或删除 cookie。 If they do this, the cookies will have no effect, regardless of the expiration date.如果他们这样做,cookie 将不起作用,无论到期日期如何。

makeCookie('rememberlogin', 'yes', { expires: -1 });

deletes the cookie.删除 cookie。 The cookie value is superfluous, and the return value false means that deletion was successful. cookie值是多余的,返回值false表示删除成功。 (A expiration of -1 is used instead of 0. If we had used 0, the cookie might be undeleted until one second past the current time. In this case we would think that deletion was unsuccessful.) (使用 -1 而不是 0 的过期时间。如果我们使用 0,则 cookie 可能会在当前时间过去一秒之前被取消删除。在这种情况下,我们会认为删除不成功。)

Obviously, since a cookie can be deleted in this way, a new cookie will also overwrite any value of an old cookie which has the same name, including the expiration date, etc. However, cookies for completely non-overlapping paths or domains are stored separately, and the same names do not interfere with each other.显然,由于可以通过这种方式删除 cookie,因此新的 cookie 也将覆盖具有相同名称的旧 cookie 的任何值,包括过期日期等。但是,完全不重叠的路径或域的 cookie 被存储分开,同名互不干扰。 But in general, any path or domain which has access to a cookie can overwrite the cookie, no matter whether or not it changes the path or domain of the new cookie.但一般来说,任何可以访问 cookie 的路径或域都可以覆盖 cookie,无论它是否更改了新 cookie 的路径或域。

rmCookie('rememberlogin');

also deletes the cookie, by doing makeCookie('rememberlogin', '', { expires: -1 }) .还通过执行makeCookie('rememberlogin', '', { expires: -1 })删除 cookie。 This makes the cookie code longer, but saves code for people who use it, which one might think saves more code in the long run.这使得 cookie 代码更长,但为使用它的人节省了代码,从长远来看,人们可能认为这会节省更多代码。

I use this to read cookie:我用它来读取cookie:

function getCookie (key) {
  let value = ''
  document.cookie.split(';').forEach((e)=>{
     if(e.includes(key)) {
        value = e.split('=')[1]
     }
  })
return value
}

let name = getCookie(name)

Using string.match .使用string.match Returns the cookie or null返回 cookie 或 null

    function checkForCookie(name) {
        let cookieString = document.cookie.match(name + '=[^;]+')
        return cookieString ? cookieString[0] : cookieString
    }

Here is an API which was written to smooth over the nasty browser cookie "API"这是一个为平滑讨厌的浏览器cookie“API”而编写的API

http://code.google.com/p/cookies/ http://code.google.com/p/cookies/

Here is an example implementation, which would make this process seamless (Borrowed from AngularJs)这是一个示例实现,它可以使这个过程无缝(从 AngularJs 借来的)

var CookieReader = (function(){
var lastCookies = {};
var lastCookieString = '';

function safeGetCookie() {
    try {
        return document.cookie || '';
    } catch (e) {
        return '';
    }
}

function safeDecodeURIComponent(str) {
    try {
        return decodeURIComponent(str);
    } catch (e) {
        return str;
    }
}

function isUndefined(value) {
    return typeof value === 'undefined';
}

return function () {
    var cookieArray, cookie, i, index, name;
    var currentCookieString = safeGetCookie();

    if (currentCookieString !== lastCookieString) {
        lastCookieString = currentCookieString;
        cookieArray = lastCookieString.split('; ');
        lastCookies = {};

        for (i = 0; i < cookieArray.length; i++) {
            cookie = cookieArray[i];
            index = cookie.indexOf('=');
            if (index > 0) { //ignore nameless cookies
                name = safeDecodeURIComponent(cookie.substring(0, index));

                if (isUndefined(lastCookies[name])) {
                    lastCookies[name] = safeDecodeURIComponent(cookie.substring(index + 1));
                }
            }
        }
    }
    return lastCookies;
};
})();

This is my simple solution:这是我的简单解决方案:

function getCookieValue(userKey){
    let items = document.cookie.split(";")
     for(item of items){
        let [key, value] = item.split("="); 
        if(key === userKey)
           return value;
    };
    return null;
}

I have come up with confusing yet very simple step after 2 hrs of concentration.经过2小时的专注,我想出了令人困惑但非常简单的步骤。

suppose a cookie 'username' is stored with a value 'John Doe'.假设 cookie 'username' 与值 'John Doe' 一起存储。

Then call readCookies('username'), this function (defined just below ) returns the value 'John Doe'.然后调用 readCookies('username'),这个函数(定义在下面)返回值 'John Doe'。

function readCookies(requestedKey){
var cookies = document.cookie;
var temporaryKeyIndex=-1,temporaryKeySet=false,temporaryKey,temporaryValue;
var  temporaryValueIndex = -1,previousTemporaryValueIndex=-2;
var readableCookie=[];
var a;
for(var i=0;i<cookies.length;i++){
    if(cookies[i]!='='&&!temporaryKeySet){
        temporaryKeyIndex++;
        temporaryValueIndex++;
    }
    else{
        temporaryKeySet = true;

        if(cookies[i]==';'||i==(cookies.length-1)){
        
                temporaryKey = cookies.slice(previousTemporaryValueIndex+2,temporaryKeyIndex+1);

        if(cookies.length>temporaryValueIndex+2){
             temporaryValue = cookies.slice(temporaryKeyIndex+2,temporaryValueIndex+1);             
        }
        else{
             temporaryValue  = cookies.slice(-((cookies.length-1) - (temporaryKeyIndex+1)))
        }

            alert('tempkey: '+temporaryKey+', reqKEY: '+requestedKey);
            
            if(requestedKey.trim()==temporaryKey.trim()){
                alert(1);
                return temporaryValue;
            }

            previousTemporaryValueIndex = temporaryValueIndex;
            temporaryKeyIndex = ++temporaryValueIndex;
            temporaryKeySet=false; 
        }
        else{
            temporaryValueIndex++;
        }
    }
}

} }

The simplest way to read a cookie I can think is using Regexp like this:我认为读取 cookie 的最简单方法是使用 Regexp,如下所示:

**Replace COOKIE_NAME with the name of your cookie. **将COOKIE_NAME替换为您的 cookie 名称。

document.cookie.match(/COOKIE_NAME=([^;]*);/)[1]

How does it work?它是如何工作的?

Cookies are stored in document.cookie like this: cookieName=cookieValue;cookieName2=cookieValue2;..... Cookie 存储在document.cookie中,如下所示: cookieName=cookieValue;cookieName2=cookieValue2;.....

The regex searches the whole cookie string for literaly "COOKIE_NAME=" and captures anything after it that is not a semicolon until it actually finds a semicolon;正则表达式在整个 cookie 字符串中搜索字面意思"COOKIE_NAME=" ,并在它之后捕获不是分号的任何内容,直到它真正找到分号;

Then we use [1] to get the second item from array, which is the captured group.然后我们使用[1]从数组中获取第二项,即捕获的组。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM