Javascript read session cookies only

。_饼干妹妹 提交于 2021-02-07 03:23:20

问题


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

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.

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

Best, Alexandre


回答1:


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).

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

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;
};

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.



来源:https://stackoverflow.com/questions/35405061/javascript-read-session-cookies-only

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!