setting cross-subdomain cookie with javascript

不问归期 提交于 2019-11-27 05:53:43

问题


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 example.com. In its current form since domain is not set, it can only be read from www.example.com


回答1:


Here is a link on how to share cookies amongst a domain:

https://www.thoughtco.com/javascript-by-example-2037272

It involves setting the domain attribute of the cookie string like:

document.cookie = "myValue=5;path=/;domain=example.com";

This cookie should now be accessible to all sub domains of example.com like login.example.com




回答2:


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



来源:https://stackoverflow.com/questions/4713019/setting-cross-subdomain-cookie-with-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!