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

 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, should the user visit a subdomain like test.example.com, we need to continue to identify the activity of the user across our "test" subdomain.

But with the current code, as soon as they leave www.example.com and visit test.example.com, they are no longer flagged as "HelloWorld".

Would anyone be able to help with my code to allow the cookie to be read across subdomains?

<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;
</script>


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>

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

mine code
document.cookie = `ul=${fu}`+expiry+'; domain=.sarkarijob.io;path=/';

change domain value as per neeed

Comments

Popular posts from this blog

cpanel exam CPSP Answers

How to install zimbra collaboration suite 8.8.11 on CentOS 7

awstats installation