Marekexp
Marekexp

Reputation: 61

How can I set a 3rd party cookie in a script served from remote domain?

It may be easy, but I never worked with cookies and the issue confuses me a little.

So let's say I have a script. It is uploaded to remote CDN. I am using it by getting it in

<script src=http://link-to-script.com/script.js></script>.

Then, I load html code with those tags and run in on localhost so it gets the script from CDN. Now, I use some of the script's function that sets a cookie within it with document.cookie. In this part I would like to have the cookie not be set on a localhost domain(which is a case right now), but on a domain that the script was served from(CDN). I want to have 3rd party cookie instead of 1st party.

What is the best possible way to do that? Could you please point me to right direction?

Upvotes: 0

Views: 1561

Answers (2)

BadPiggie
BadPiggie

Reputation: 6359

You can only set cookie for current domain and it's sub-domains.

For-Example:

You can create cookie for a.mydomain.com , b.mydomain.com, c.mydomain.com from mydomain.com.

You can't create cookie for mydomain.com from anotherdomain.com.


Cross-Domain Cookies

But if you want to create cookie for another domain, You need to redirect to that particular URL and create cookie from that site.

OR

If you want to create cookie for another domain, you can try this,

<img src='http://www.anotherdomain.com/createCookie.php'>

Upvotes: 0

D Mishra
D Mishra

Reputation: 1578

Hey you can refer Can a 3rd party js script write cookies?

To write third-party cookies (i.e. where the cookie is on the domain of the third party) requires that the cookies be sent in the headers of a download from that third party, and not written by JS code.

Write below code in request headers, MDN reference link https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie

Set-Cookie: <cookie-name>=<cookie-value> 

Upvotes: 1

Related Questions