If you want to set cookie on your domain, you can do this by few lines of codes just using JS. But the problem arises when you want to set cross domain cookie(s).
Say, you have three domains.
Now when someone enters to
ainixon.me, I set a cookie (say,
visited:nixon's site) for the domain. So that I can show some info based on cookie.
Now I also need to set same cookie to my others domains. So that I can serve same info as
ainixon.me in those domains too.
Now the question is how to set cookie from a domain to some other domains?
We can't send a ajax request from one domain to another domain since mordern browser will block these request for cross domain requesting.
There could be many solutions for this kind of problem. But I have find out a simple solution. I hope it'll save some other developers valuable time.
Say, the sites in three domains are running in PHP.
First I place a PHP code in a script called
setcookie("visited", "nixon's site", time()+3600);
Now on the domain
ainixon.me the HTML code will be look like the following code
<!DOCTYPE html> <html> <head> <script> //place set cookie for own domain here // // </script> </head> <body> <!-- setting cookies to other domains --> <img src="https://anotherdomain.com/cookies.html" style="display:none;" /> <img src="https://somedomain.ne/cookies.html" style="display:none;" /> <!-- setting cookies to others domains ends --> <!-- place other htmls here --> </body> </html>
So, when someone visits
ainixon.me,it will request a pages from other domain as images. As the pages are not images they will set cookies for those domain in the browser. And the browser allows it too.
This is how Google, Microsoft etc. set cookies for their multiple domains. Say you logged into gmail.com, it'll set cookie like this to youtube.com, google.com etc.