0

I am seeing lots and lots of functions for reading cookies in via java script, but I only want to use it once and inside a variable, I am new to JS.

Here is my code

var TheNumber = (Math.random() + '') * 1000000000000000000;
document.cookie= "rand=" + TheNumber.toString() + ";path=/";
var AdServer = {
    tile: 1,
    mock: false,
    ord: (Math.random() + "") * 1000000000000000000 + '?',

I want to replace the ord part with the value from the rand cookie.

Could you guide me on the following: Do I need a function? If so where do I put it? How would I call it?

6
  • Take a look at this site: w3schools.com/js/js_cookies.asp Commented Jun 7, 2012 at 21:18
  • @frenchie Got that open in a tab... Because its inside a var I am unsure on what to do? Commented Jun 7, 2012 at 21:20
  • Are you looking for AdServer.ord = TheNumber; ? Not sure what you're trying to do. Try alert(AdServer.ord) and see if that's what you're looking for. AdServer is just an object that contains properties. Commented Jun 7, 2012 at 21:22
  • var AdServer = {title: 1, mock: false, ord: TheNumber}? Commented Jun 7, 2012 at 21:23
  • yes, that'll work too. Make sure to add the semi-colon at the end. Commented Jun 7, 2012 at 21:23

1 Answer 1

2

I find the easiest (and most flexible) way to write/read from cookies with JavaScript is with global object with getter/setter methods.

The Mozilla dev docs page on document.cookie has a well documented example: https://developer.mozilla.org/en/DOM/document.cookie

How/where you might instantiate and then reference that object depends on the rest of your program, but assuming for simplicity we're just in the global namespace and aren't worried about variable collision etc:

var docCookies = {
    getItem: function (sKey) {  
      if (!sKey || !this.hasItem(sKey)) { return null; }  
      return unescape(document.cookie.replace(new RegExp("(?:^|.*;\\s*)" + escape(sKey).replace(/[\-\.\+\*]/g, "\\$&") + "\\s*\\=\\s*((?:[^;](?!;))*[^;]?).*"), "$1")); 
    },
    setItem: function (sKey, sValue, vEnd, sPath, sDomain, bSecure) {  
      if (!sKey || /^(?:expires|max\-age|path|domain|secure)$/.test(sKey)) { return; }  
      var sExpires = "";  
      if (vEnd) {  
        switch (typeof vEnd) {  
          case "number": sExpires = "; max-age=" + vEnd; break;  
          case "string": sExpires = "; expires=" + vEnd; break;  
          case "object": if (vEnd.hasOwnProperty("toGMTString")) { sExpires = "; expires=" + vEnd.toGMTString();  } break;  
        }  
      }  
      document.cookie = escape(sKey) + "=" + escape(sValue) + sExpires + (sDomain ? "; domain=" + sDomain : "") + (sPath ? "; path=" + sPath : "") + (bSecure ? "; secure" : "");  
    },
  hasItem: function (sKey) { return (new RegExp("(?:^|;\\s*)" + escape(sKey).replace(/[\-\.\+\*]/g, "\\$&") + "\\s*\\=")).test(document.cookie); }  
}

Then set your cookie with:

docCookies.setItem('rand', (Math.random()* 1000000000000000000).toString());

And get it with:

docCookies.getItem('rand');

So to put it all together:

var docCookies = {
    getItem: function (sKey) {  
      if (!sKey || !this.hasItem(sKey)) { return null; }  
      return unescape(document.cookie.replace(new RegExp("(?:^|.*;\\s*)" + escape(sKey).replace(/[\-\.\+\*]/g, "\\$&") + "\\s*\\=\\s*((?:[^;](?!;))*[^;]?).*"), "$1")); 
    },
    setItem: function (sKey, sValue, vEnd, sPath, sDomain, bSecure) {  
      if (!sKey || /^(?:expires|max\-age|path|domain|secure)$/.test(sKey)) { return; }  
      var sExpires = "";  
      if (vEnd) {  
        switch (typeof vEnd) {  
          case "number": sExpires = "; max-age=" + vEnd; break;  
          case "string": sExpires = "; expires=" + vEnd; break;  
          case "object": if (vEnd.hasOwnProperty("toGMTString")) { sExpires = "; expires=" + vEnd.toGMTString();  } break;  
        }  
      }  
      document.cookie = escape(sKey) + "=" + escape(sValue) + sExpires + (sDomain ? "; domain=" + sDomain : "") + (sPath ? "; path=" + sPath : "") + (bSecure ? "; secure" : "");  
    },
  hasItem: function (sKey) { return (new RegExp("(?:^|;\\s*)" + escape(sKey).replace(/[\-\.\+\*]/g, "\\$&") + "\\s*\\=")).test(document.cookie); }  
}
//set our cookie
docCookies.setItem('rand', (Math.random()* 1000000000000000000).toString());

then later/elsewhere in your code when you want to retrieve the cookie value:

var AdServer = {
    tile: 1,
    mock: false,
    ord: docCookies.getItem('rand')
};

Now if you inspect AdSever.ord it will equal the random number from your rand cookie that you set earlier.

console.log(AdServer.ord);
Sign up to request clarification or add additional context in comments.

3 Comments

Thank you that seems like a cleaner way to do things, but please can you explain where I would insert that into my code, so that the ord: takes the value of the cookie?
Sure thing, I've edited my answer to explain how to get the cookie value into your AdSever object.
Thank you! I will use this all the time from now on, its a clean way to do things.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.