How To Set Same Cookie On Different Domains


Read {count} times since 2020

You might have seen sites like Google setting the login status cookie on the various domains of theirs (YouTube, Blogger). As you may know, cookie can’t be set in a different domain from another domain directly.

If you’re having multiple sites in where you need to set a cookie from a parent site, you can use basic **HTML **and JS to set the cookies. Google is using this same way.

Domains

For this tutorial, we will refer to three domains :

www.example.com
www.mysite.com
www.india.com

We will set cookies on mysite.com and india.com from example.com.

Other Domains

You should make a dynamic page named “setCookie.php” on your server where you’re going to create the cookie. If it’s PHP, then add the following code to set the cookie :

<?
setcookie("MyCookie", "subinsb.com", time()+3600);
?>

In the above case we’re not mentioning the path or domain because PHP automatically sets it.

Main Domain

On the main domain (example.com) where you’re going to ask the other two domains to set the cookie, create an HTML page with the following content :

<!DOCTYPE html>
<html>
 <head>
  <script>
   function loadComplete(){
    alert("Completed Setting Cookies");
   }
  </script>
 </head>
 <body onload="loadComplete()">
  <p>
  Please Wait...
  </p>
  <img src="http://www.mysite.com/setCookie.php" style="display:none;" />
  <img src="http://www.india.com/setCookie.php" style="display:none;" />
 </body>
</html>

When the client visits the above page, a page is requested from the mysite.com domain as image source, but the page is not an image. This page that is on the other domain will set the cookie on that domain.

We also add an event listener on the document, so that we will know when the cookies are set completely. This is equal to document loaded listener because when the images are loaded, cookies are set.

Other Things

You can also send data to the other domains as GET parameters so that cookies based on that data can be created. But, when you send passwords or other secure content, be sure to encrypt the string.

The images should be hidden because, since it’s not valid images, the ugly image icon will appear in the browser.

You can change the content of the event listener callback loadComplete() to do something else according to your choice, like redirecting back to the main domain.

How Google Do It

If you have account on Blogger & YouTube which are on external domains, when you log in via accounts.google.com you are redirected to a page that says “Please Wait…”, right ? If you look at the source code of the page, you can see the tags of youtube.com and blogger.com domain. Yes, Google is using the same way to set login information cookie on YouTube and Blogger.

Microsoft does in this same way to set cookies on their services like Hotmaillive.commsn.com etc.. So many domains, right ?

Show Comments