简体   繁体   English

只能通过特定 URL 访问的 Cookie

[英]Cookie accessible only by specific URL

我想使用 javascript 获取和设置 cookie,但希望它们只能被设置它们的页面访问(即 cookie 是页面私有的,因此其他页面不能干扰或读取它们)。

Here's what you need to do :这是你需要做的:

Suppose you are on the page with url http://www.example.com/pages/myPage.html , and you want to limit the access to cookies on this particular page ( myPage.html ) only then while setting/creating the cookie you have the set the path parameter as current page relative path .假设您在具有 url http://www.example.com/pages/myPage.html的页面上,并且您只想在设置/创建 cookie 时限制对该特定页面 ( myPage.html ) 上的 cookie 的访问您已将路径参数设置当前页面相对路径

var pathToMyPage = window.location.pathname; // this gives pages/myPage.html
document.cookie('name=value;path='+ pathToMyPage); 

Now if you try to look for this particular key in the cookie of other pages say /pages/myPage2.html .现在,如果您尝试在其他页面的 cookie 中查找此特定键,请说/pages/myPage2.html You won't find it there.你不会在那里找到它。

You can't limit it to a particular URL, but what you can do is limit it to a path (relative to your domain).您不能将其限制为特定 URL,但您可以将其限制为path (相对于您的域)。

For a trick if you only have a single page inside a particular folder and set the path accordingly , the cookie will be accessible to only that page.对于一个技巧,如果您在特定文件夹中只有一个页面并相应地设置路径,则 cookie 将只能被该页面访问。

Refer tothis post to know more about cookies.请参阅此帖子以了解有关 cookie 的更多信息。

The javascript code to set a cookie will be设置 cookie 的 javascript 代码将是

document.cookie="username=something ; expires=Thu, 18 Dec 2014 12:00:00 GMT; path=/blog";

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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