如何使用javascript获取cookie的路径 [英] How to get cookie's path using javascript

查看:71
本文介绍了如何使用javascript获取cookie的路径的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的设置Cookie js功能

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

当我创建一个cookie时,

When I create a cookie,

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

如何获取cookie的路径?

How to get cookie's path?

推荐答案


TL:DR;
您无法使用javascript根据路径阅读Cookie。

在JavaScript中,您只能设置或获取使用内部对象的cookie document.cookies 此对象的内容将是一串非httpOnly cookie名称和值由分隔; 。这就是它。

In JavaScript, you can only set or get cookies by using the internal object document.cookies. 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.

你无法获得 Path Domain 以及 cookies 的其他属性,因为它们只能被浏览器读取而不会显示给JavaScript。

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.

另一方面,如果您使用任何形式的AJAX,您可以尝试通过 xhr.getResponseHeader(Set-Cookie)来拦截和解析请求标头并存储根据您的需要, localStorage sessionStorage 中的值。我仍然告诉你,这不是一个好主意。某些浏览器可能会将 Set-Cookie 标头视为javascript要读取的禁止标头之一。但我认为限制只适用于 httpOnly cookies。

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.

这篇关于如何使用javascript获取cookie的路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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