Hello. The site learn.javascript.ru says that you can specify either the main domain or its subdomain in the domain parameter, but I cannot create a one.example.com for one.example.com from example.com .

I know about the point in front of the domains. Interested in creating cookies for one subdomain, being on the main domain.

Example: being on the javascript.ru website create a cookie accessible only to learn.javascript.ru :

 var date = new Date(new Date().getTime() + 60 * 1000); document.cookie = "name=value; domain=learn.javascript.ru; path=/; expires=" + date.toUTCString(); 

    1 answer 1

    It is created here only if you do not take into account that it is immediately removed. From the same article.

    If the date is in the past, the cookie will be deleted.

    You specify a date equal to the current time. That's how it should work. Cook will live an hour.

     var date = new Date(new Date().getTime() + 60 * 1000); document.cookie = "test=test; domain=learn.javascript.ru; path=/; expires=" + new Date(date.getTime()+3600).toUTCString(); 

    Also note that your experiments will only work if you use the developer console on the same domain . You cannot issue cookies to one domain from another.

    UPD.

    I did not understand you much. learn.javascript.ru and javascript.ru are different domain names. Being on javascript.ru you can only set a cookie for all .javascript.ru subdomains, by the fact that this is still the "scope" of this domain. However, a.javascript.ru is an independent domain with its own scope. You can no longer give him a cookie.

    But,

    If we take a real case, imagine that you have several subdomains and you really need to set a cookie for one specific domain, for example forum.somesitename.local .

    Being on somesitename.local You can send ajax request for example to forum.somesitename.local/?getCookie=on , the server will know that you need to get a cookie for this domain and return the header with Set-Cookie

    And yet, you will not be able to get the forum.somesitename.local with somesitename.local if there are no corresponding headers on the server .

    • Thanks for the answer. And you can specify exactly how the browser verifies the correctness of the domain parameter. - Fapalz
    • That is, being on the site somesitename.local in the domain parameter will be valid only somesitename.local . If you are at forum.somesitename.local then the valid values ​​will be forum.somesitename.local and somesitename.local . Is there any documentation describing domain validation? - Fapalz