setting cross-subdomain cookie with javascript

前端 未结 2 1034
情书的邮戳
情书的邮戳 2020-12-06 09:23

How should I add domain support to these functions? I want to achieve that .example.com is declared as domain, so that the cookies can be read across all subdomains of the e

2条回答
  •  盖世英雄少女心
    2020-12-06 09:36

    In my case we needed to set a cookie that would work across our .com subdomains:

    function setCrossSubdomainCookie(name, value, days) {
      const assign = name + "=" + escape(value) + ";";
      const d = new Date();
      d.setTime(d.getTime() + (days*24*60*60*1000));
      const expires = "expires="+ d.toUTCString() + ";";
      const path = "path=/;";
      const domain = "domain=" + (document.domain.match(/[^\.]*\.[^.]*$/)[0]) + ";";
      document.cookie = assign + expires + path + domain;
    }
    

    This might not work for .co.uk etc but the principle can be used

提交回复
热议问题