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).
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 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";
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With