最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - make cookie persist across subdomain - Stack Overflow

programmeradmin2浏览0评论

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 with a tag like so: example/?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. 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?

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. with a tag like so: example./?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.. 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?

Share Improve this question asked Apr 23, 2015 at 12:55 Doug FirDoug Fir 21.4k54 gold badges191 silver badges340 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 6

Domain should be something like .example. so *.example. 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."

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

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

Duplicate here: setting cross-subdomain cookie with javascript

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

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

发布评论

评论列表(0)

  1. 暂无评论