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 user3328211user33282112 Answers
Reset to default 3Here'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";