最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Cookie accessible only by specific URL - Stack Overflow

programmeradmin1浏览0评论

I want to get and set the cookie using javascript, but want them only to be accessible to the page that set them (i.e the cookie is private to the page, so no other pages can interfere or read them).

I want to get and set the cookie using javascript, but want them only to be accessible to the page that set them (i.e the cookie is private to the page, so no other pages can interfere or read them).

Share Improve this question edited Mar 25, 2021 at 22:02 Wang Liang 4,4447 gold badges26 silver badges50 bronze badges asked Mar 8, 2014 at 6:59 user3328211user3328211
Add a ment  | 

2 Answers 2

Reset to default 3

Here's what you need to do :

Suppose you are on the page with url http://www.example./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 to this 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";
发布评论

评论列表(0)

  1. 暂无评论