Say I have a website called a.com
, and when a specific page of this site is loaded, say page link, I like to set a cookie for another site called b.com
In case you have a.my-company.com
and b.my-company.com
instead of just a.com
and b.com
you can issue a cookie for .my-company.com
domain - it will be accepted and sent to both of the domains.
Setting cookies for another domain is not possible.
If you want to pass data to another domain, you can encode this into the url.
a.com -> b.com/redirect?info=some+info (and set cookie) -> b.com/other+page
You can't, but... If you own both pages then...
1) You can send the data via query params (http://siteB.com/?key=value)
2) You can create an iframe of Site B inside site A and you can send post messages from one place to the other. As Site B is the owner of site B cookies it will be able to set whatever value you need by processing the correct post message. (You should prevent other unwanted senders to send messages to you! that is up to you and the mechanism you decide to use to prevent that from happening)
You can't, at least not directly. That would be a nasty security risk.
While you can specify a Domain attribute, the specification says "The user agent will reject cookies unless the Domain attribute specifies a scope for the cookie that would include the origin server."
Since the origin server is a.com
and that does not include b.com
, it can't be set.
You would need to get b.com
to set the cookie instead. You could do this via (for example) HTTP redirects to b.com
and back.
Here is what I've used. Note, this cookie is passed in the open (http) and is therefore insecure. I don't use it for anything which requires security.
You could probably add encryption/signatures to make this secure. Do your research on how to do that correctly.