简体   繁体   中英

How to get cookie's path using javascript

My set Cookie js function

function setCookie(name, value, expires, path){
    cookieStr = name + "=" + escape(value) + "; ";

    if(expires){
        expires = setExpiration(expires);
        cookieStr += "expires=" + expires + "; ";
    }
    if(path){
        cookieStr += "path=" + path + "; ";
    }
    document.cookie = cookieStr;
}

When I create a cookie,

 setCookie('MyCookie','cookieName',3,'/Members')

How to get cookie's path?

TL:DR; You cannot read through cookies based on path using javascript.

In JavaScript, you can only set or get cookies by using the internal object document.cookie . And the content of this object will be a string of key value pairs of non-httpOnly cookie names and values separated by a ; . And that is pretty much it.

There is no way you could get a trace of Path , Domain and other attributes of cookies as they are only read by browsers and not shown to JavaScript.

On the other hand, If you are using any form of AJAX, You could try to intercept and parse the request headers by xhr.getResponseHeader("Set-Cookie") and store the value in localStorage or sessionStorage as per your need. I still advise you that it is not a good idea. Some of the browsers might consider Set-Cookie header as one of the forbidden headers to be read by javascript. but I think that restriction is only for httpOnly cookies.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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