3

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

Wang Liang
  • 4,244
  • 6
  • 22
  • 45

2 Answers2

3

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.

bhavya_w
  • 9,186
  • 9
  • 29
  • 38
  • Hi but what if i want to limit the usage of cookies to only on `http://www.example.com` and not on the other domain? – Shift 'n Tab Oct 23 '19 at 10:49
  • @Roel, Cookies by default are set specific to the domain. So, if you set cookies for say http://www.example.com, you won't find those cookies under https://google.com. – bhavya_w Oct 24 '19 at 08:54
  • I have seen some article that you can pass cookies to other site if you don't provide the samesite option or `samesite="lax"` may also submit your cookie to other site. Although my knowledge is still limited. – Shift 'n Tab Oct 24 '19 at 08:58
  • 1
    @Roel, please check this link - https://stackoverflow.com/questions/6761415/how-to-set-a-cookie-for-another-domain – bhavya_w Oct 24 '19 at 09:29
1

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";
Shiva
  • 6,677
  • 4
  • 36
  • 61