Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
115 views
in Technique[技术] by (71.8m points)

How to get the domain value for a cookie in Javascript?

Using Javascript I'd like to get the domain value for a specific cookie.

Is this possible? If so, how?

To clarify: I'm not looking for the value of the cookie. I'm on "subdomain.domain.com" and I need to remove a cookie whose name is known but its domain value is something like ".domain.com". In short: I'd like to get the value of ".domain.com".

question from:https://stackoverflow.com/questions/2959010/how-to-get-the-domain-value-for-a-cookie-in-javascript

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Sorry, all you get is what you see in document.cookie. The cookie metadata like path, domain and expires are not visible to site code (neither to JavaScript nor to the server-side).

To read a cookie that is being shadowed by a cookie with a more-specific domain or path, the only thing you can do is load a page for which the more-specific cookie is out-of-scope, and read it from there.

If, as you say, you only need to remove a cookie, what you could do is try to remove the cookie at every possible level of specificity, eg.:

    document.cookie= 'foo=;domain=sub.domain.example.com;expires=Sat, 01-Jan-2000 00:00:00 GMT';
    document.cookie= 'foo=;domain=domain.example.com;expires=Sat, 01-Jan-2000 00:00:00 GMT';
    document.cookie= 'foo=;domain=example.com;expires=Sat, 01-Jan-2000 00:00:00 GMT';

and similarly with the path variable. You could put this in a nested loop for each path and domain part, splitting on . for the domain and / for the path.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...