6

I am trying to set cookie to domain same as src of js file.

Scenario: In www.xyz.com html, I have included js file from qwe.com as below

<script type="application/javascript" src="http://qwe.com/b.js"></script>

From this b.js, i want to create cookie with domain set to .qwe.com. I am setting cookie with following function

function createCookie(name, value, days) {
    if (days) {
      var date = new Date();
      date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
      var expires = "; expires=" + date.toGMTString();
    } else {
      var expires = "";
    }
    document.cookie = name+"="+value+expires+";domain=.qwe.com"+"; path=/;";
  }

With above code I am unable to set cookie. Example: www.flipkart.com-> Check cookies in resources tab of developer console-> .scorecardresearch.com and .doubleclick.net are able to set cookie

I want to do same. Can someone please share solution for this? Real working solution. I have tried multiple solutions by doing Google search. It didn't work.

User19380
  • 63
  • 1
  • 1
  • 5

1 Answers1

11

Client side JavaScript can set cookies only for the domain the webpage is hosted on.

The examples you cite use HTTP headers to set cookies, not JavaScript.

Community
  • 1
  • 1
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
  • Hey Quentin, thanks for reference. I am a beginner at very early stage. Can you please explain a bit? How to accomplish it using HTTP headers to set cookies? I checked another answer on HTTP headers [link](http://stackoverflow.com/questions/1062963/how-do-browser-cookie-domains-work). It seems it can not be accomplished with it. Please help in clarification. – User19380 Jun 26 '15 at 17:46
  • 1
    How you set HTTP headers depends on the server side language you use on the server. That link is about setting headers for a different domain, you aren't trying to do that: Script comes from example.com, cookies set for example.com. – Quentin Jun 26 '15 at 19:49
  • Got it! Thanks for your input! – User19380 Jun 26 '15 at 19:52