Creating a JavaScript cookie on a domain and reading it across sub domains

前端 未结 4 458
感动是毒
感动是毒 2020-11-27 10:21

Below is a JavaScript cookie that is written on the user\'s computer for 12 months.

After we set the cookie on our main domain such as example.com, shou

相关标签:
4条回答
  • 2020-11-27 10:55

    You want:

    document.cookie = cookieName +"=" + cookieValue + ";domain=.example.com;path=/;expires=" + myDate;
    

    As per the RFC 2109, to have a cookie available to all subdomains, you must put a . in front of your domain.

    Setting the path=/ will have the cookie be available within the entire specified domain(aka .example.com).

    0 讨论(0)
  • 2020-11-27 11:12

    You can also use the MDN JavaScript Cookie Framework and do:

    docCookies.setItem('HelloWorld', 'HelloWorld', myDate, '/', 'example.com');
    
    0 讨论(0)
  • 2020-11-27 11:15

    Just set the domain and path attributes on your cookie, like:

    <script type="text/javascript">
    var cookieName = 'HelloWorld';
    var cookieValue = 'HelloWorld';
    var myDate = new Date();
    myDate.setMonth(myDate.getMonth() + 12);
    document.cookie = cookieName +"=" + cookieValue + ";expires=" + myDate 
                      + ";domain=.example.com;path=/";
    </script>
    
    0 讨论(0)
  • 2020-11-27 11:15

    Here is a working example :

    document.cookie = "testCookie=cookieval; domain=." + 
    location.hostname.split('.').reverse()[1] + "." + 
    location.hostname.split('.').reverse()[0] + "; path=/"
    

    This is a generic solution that takes the root domain from the location object and sets the cookie. The reversing is because you don't know how many subdomains you have if any.

    0 讨论(0)
提交回复
热议问题