简体   繁体   中英

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 .

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

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.

Refer tothis post to know more about cookies.

The javascript code to set a cookie will be

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

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