仅Javascript读取会话Cookie [英] Javascript read session cookies only

查看:49
本文介绍了仅Javascript读取会话Cookie的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否有现有的技巧可以对Cookie进行过滤.我只需要获取会话cookie,而丢弃其他cookie.使用Javascript读取Cookie的常用方法是:

I am wondering if there is an existing trick to filter on the cookies. I need to get the session cookies only and to discard the other. The usual way to read cookies using Javascript is:

document.cookie

但是,这会打印所有cookie,我的目标是仅获取会话cookie.我知道,与普通" Cookie不同,会话Cookie的有效期限是

However this prints all the cookies, my goal here is to get the session cookies only. I know that unlike "normal" cookies a session cookie has an expiration date.

有人有代码示例来实现此会话Cookie的提取吗?

Does anyone have a code sample to achieve this session cookies extraction?

最好,亚历山大(Alexandre)

Best, Alexandre

推荐答案

会话cookie" 正常的cookie.它可能有(也可能没有)有效期,但是没有什么可以阻止其他cookie也具有有效期.识别会话cookie的唯一可靠方法是知道它的名称(当然,这取决于网站,但是如果它是您的网站则不是问题).

A "session cookie" is a normal cookie. It may (or may not) have an expiration date but nothing prevents other cookies to have an expiration date as well. The only reliable way to identify a session cookie is if you know its name (this is website-dependent of course, but isn't a problem if this is your website).

此外,您无法通过Java脚本了解Cookie的到期日期.

Also, you have no way of knowing a cookie's expiration date from Javascript.

现在, document.cookie 为您提供所有cookie,以分号分隔的字符串.您只需要按分号将其分解即可检索键值对.因此,以下是一个示例代码,用于查找具有其名称的Cookie:

Now document.cookie gives you all cookies as a semi-colon delimited string. You just need to break it down on semi-colons to retrieve the key-value pairs. So here's a sample code to look for a cookie given its name:

var getCookie = function(name) {
    var cookies = document.cookie.split(';');
    for(var i=0 ; i < cookies.length ; ++i) {
        var pair = cookies[i].trim().split('=');
        if(pair[0] == name)
            return pair[1];
    }
    return null;
};

如果您不知道会话cookie的名称,那么您就不走运了.时期.您可能会找到聪明的启发式方法来确定它是哪一种(基于名称和/或值的形式),但是对于所有具有100%置信度的网站,没有任何信息可以准确告诉您哪个cookie是会话cookie,以及是否有一个完全没有.

If you don't know the session cookie's name you're out of luck. Period. You could maybe find clever heuristics to determine which one it is (based on the form of name and/or value), but nothing can tell you exactly for all websites with 100% confidence which cookie is the session cookie, and if there is one at all.

这篇关于仅Javascript读取会话Cookie的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆