3

I set a cookie:

<script>
  document.cookie="cid1={{utm_campaign}}; path=/;"
</script>

The {{}} is a macro and is Google-Tag-Manager syntax, please ignore that.

The script above is triggered whenever anyone lands on example.com with a tag like so: example.com/?utm_medium=test&utm_source=bla&utm_campaign=foo. I tested it and sure enough, when I land on the home page with these parameters the cookie is set.

But a visitor can move to a subdomain dogs.example.com. When I looked in the console the cookie cid1 is no longer there.

Is there a setting I can change when creating the cookie other than setting the path to "/" so that the cookie crosses to the subdomain?

Doug Fir
  • 14,921
  • 39
  • 121
  • 228

2 Answers2

6

Domain should be something like .example.com so *.example.com can access it

var website_host = window.location.hostname.replace('www.', '');
document.cookie = "cid1={{utm_campaign}}; path=/;domain=."+website_host 

// to be something like this"cid1={{utm_campaign}}; path=/;domain=.example.com"
mohamed-ibrahim
  • 9,510
  • 3
  • 35
  • 47
  • Thank you for the answer this was really easy. For the record I did search Google and Stack Overflow first but there was no results for a baby step like this, only more advanced cookie usage. Accepting shortly – Doug Fir Apr 23 '15 at 13:05
4

You're missing the domain-parameter for this. Set domain to .example.com to make it accessable from all pages in .example.com.

<script>
  document.cookie="cid1={{utm_campaign}}; path=/; domain=.example.com"
</script>

Duplicate here: setting cross-subdomain cookie with javascript

;domain=domain (e.g., 'example.com', '.example.com' (includes all subdomains), 'subdomain.example.com') If not specified, defaults to the host portion of the current document location.

Full documentation: https://developer.mozilla.org/en-US/docs/Web/API/Document/cookie

Community
  • 1
  • 1
PWL
  • 507
  • 3
  • 21