How to set a global cookie in JavaScript?
Asked Answered
L

3

5

I've created a Django website, and need a cookie to be stored and readable from any part of the site. The JavaScript for it is in every part I need it in, but for some reason the cookie itself is stored seperately for each page. E.g. if the cookie is equal to "set" on one page, it can be undefined on another. Here's the code I'm using to create, get, and read the cookie (the "createBannerCookie()" method is called when a specific button, found on every page, is pressed)-

<script type="text/javascript">
$(document).ready(function() {
  $('#banner').hide();
  checkBannerCookie();
});

function createBannerCookie() 
{
  $('#banner').hide();
  var exdate=new Date();
  exdate.setDate(exdate.getDate() + 3);
  var c_value=escape("set") + ((exdate==null) ? "" : "; expires="+exdate.toUTCString());
  document.cookie='banner=' + c_value;
}

function getCookie(c_name)
{
  var i,x,y,ARRcookies=document.cookie.split(";");
  for (i=0;i<ARRcookies.length;i++)
  {
    x=ARRcookies[i].substr(0,ARRcookies[i].indexOf("="));
    y=ARRcookies[i].substr(ARRcookies[i].indexOf("=")+1);
    x=x.replace(/^\s+|\s+$/g,"");
    if (x==c_name)
    {
      return unescape(y);
    }
  }
}

function checkBannerCookie()
{
  var banner=getCookie("banner");
  if (banner!=null && banner!="")
  {
    $('#banner').hide();
  }
  else 
  {
    $('#banner').show();
  }
}
</script>

Any suggestions?

Loathsome answered 8/8, 2012 at 16:12 Comment(0)
B
20

By default, cookies are accessible only to web pages in the same directory as the web page which originally created the cookie. Please try to add "path=/" option. e.g.

document.cookie =
  'propertyName=test; path=/'
Bourbon answered 8/8, 2012 at 16:39 Comment(0)
S
0

SImon,

I think your problem is the expiration date on your cookies. It looks to me like you are setting them to expire 3 miliseconds after being created.

Try something like this in your "createBannerCookie" function (instead of the w3schools version):

function createBannerCookie() 
{
  $('#banner').hide();
  var exdate=new Date();
  exdate.setTime(exdate.getTime()+(3*24*60*60*1000)); // the 3 in that math is your days
  var c_value=escape("set") + ((exdate==null) ? "" : "; expires="+exdate.toUTCString());
  document.cookie='banner=' + c_value;
}

Reference: http://www.quirksmode.org/js/cookies.html

Simarouba answered 8/8, 2012 at 16:33 Comment(1)
This doesn't seem to be working either - if this was the case, the cookies wouldn't work on only some pages.Loathsome
F
0

You can set a cookie with the global path / (a global cookie) by adding ;path=/ as shown below. *Without spcifying a path, a cookie is set with a random path depending on url:

                                      // ↓↓↓↓↓↓↓
document.cookie = 'cookieName=cookieValue;path=/'
Fellowman answered 10/7, 2023 at 14:51 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.