Actionscript Cookie Util

November 12, 2008

Hi folks,

a lot of time has gone by since my last post, I’m quite busy at the moment. But this didn’t stop me from setting up this post. I have written a small utility class which I think some of you really would like to use. It is a small class that makes it possible to set Cookies via Actionscript without adding anything to the HTML Wrapper, all the code will be injected at runtime.

I have packaged the whole thing as a ready to use flex project but feel free to use it in any other Actionscript 3 environment (Flash or pure AS3). You can grab the files here http://depositfiles.com/files/ry60vxfh8

The Util comes with methods for setting, getting and removing cookies – as mentioned before you do not have to change a single line in your wrapper, just import the class and start setting cookies from flash or flex. I have made this util because of some concerns using Flash Cookies (Shared Objects) with Internet Explorer 6 – now i do not use Shared Objects anymore if I do not really need them. I really do not know why this doesn’t come with any of the Adobe utils.

To use the util, download the file and put the de/aggro/utils/CookieUtil into your source folder, then try the following:

import de.aggro.utils.CookieUtil;
//Set a cookie named mycookie with a value of mycookie value with a time to live of 30 days
CookieUtil.setCookie("mycookie", "mycookie value", 30);
//Get that cookie and trace its value
trace(CookieUtil.getCookie("mycookie"));
//Delete the cookie from the users computer
CookieUtil.deleteCookie("mycookie");

Feel free to use the util for any commercial, private or educational purposes and drop me a comment if you like it.

56 Responses to “Actionscript Cookie Util”

  1. Olivier Says:

    Hi,

    I’m very much interested by your post.
    Unfortunately, it looks like the link for accessing the CookieUtil class is broken..

    Would you mind sending me this file?

    Best regards, Olivier.

  2. kingschnulli Says:

    Hmm,

    I think you should look at your browser settings this link works perfectly fine for me. I’ll drop you an email with the file.

  3. Aran Says:

    “I have made this util because of some concerns using Flash Cookies (Shared Objects) with Internet Explorer 6 – now i do not use Shared Objects anymore if I do not really need them”

    Can you elaborate on this? What is the issue with IE6 and LSO?

  4. kingschnulli Says:

    I have an application that needed to store a specific id on the users computer which will then be read in another flash application. This has worked about 6 Month without any issues but then someday it refused to store LSO’s on a users computer if he used IE6 (have tested that on several different workstations and under XP/2000). I looked into the folder on the users computer if the LSO was written, but it wasn’t. I checked the Flash Player Settings Manager and everything was configured fine, it was working with FF3 and FF2 on the same computer o0. I finally gave up storing LSO’s for an increment value, I think I’m better of using the CookieUtil and for more complex data some serialisation technique.

    Also many users are complaining that LSO’s are a security risk because it doesn’t get flushed with the browser cache.

    What do you need to store with the LSO ?

  5. Russ Says:

    This is pretty slick, I will have to give it a try. Do cookies only take string values, or can you set objects as well? That is one advantage to LSO.

  6. kingschnulli Says:

    You can serialize the stuff you want to store in the cookie, look at adobes URLUtil that will do the conversion for you.

  7. James Says:

    I just tried writing one of these myself and came up against a wall of problems. This solves it very nicely – brilliant.

  8. reinhard Says:

    download is not working

  9. kingschnulli Says:

    I do not know what browser you are using but deposit files works perfectly fine for me. Try to copy/paste the link into your browser bar.

  10. Charlie Says:

    Great hack. Surprising that it works; but it’s quite useful. Thanks!

  11. Hari Says:

    Hi,
    Thanks a lot for this post.

    Really fantastic stuff. Great man

    Regards

  12. Sjoedzj Says:

    Nice One


  13. [...] in:flex Blog (http://myflex.wordpress.com/2008/11/12/actionscript-cookie-util/) has an excelent, fully featured, self-contained ActionScript 3.0 class library for reading, [...]

  14. Bob Says:

    Thanks for this, saved my arse today!

  15. Tommy Says:

    Hey Hi,

    I am quite new probably at whole as3 but can someone please explain me bit to bit how can I implement this whole code into my Flash CS3 as3 ?
    I have tried to include but don’t know how and I just get bunch of errors :(
    Please, I really need for my movie this code but cannot use it :(
    I would appreciate if someone can help me. Huge THANK YOU in advance.

    Tommy

    • kingschnulli Says:

      It should work out of the box, just be sure to include the de/aggro… folder into your classpath. There are plenty tutorials out there showing you how to add classes to your classpath. I’m not developing Flash CS3 only Flex so I can not really tell you what to do exactly.

  16. Abdul Areef Says:

    Hi,

    i am facing cookies problem in my Application,

    if i send the request to server in first time means, its going to the server

    but in second time, its not going. instead of its getting the data from the cache itself, i want to remove the cache in my system, is it possible

    i need suggestion/solution

    thanks
    areef

    • kingschnulli Says:

      Try setting a no cache header if you contact the server for the first time or append a random var value to every request you make, that should fix you caching issues.

  17. Eric Says:

    I tried the cookie code you provided, but the trace only returns ‘null’. I am developing on a Mac… could there be a pathing issue?

    • kingschnulli Says:

      Right now I am developing under os x 10.5.3 and it works fine for me, I think it might relate to some browser security issue – what browser are you trying and did you allow scriptaccess for the movie ?

  18. Eric Says:

    Thank you for solving a critical problem. I’ve played around with some solutions but none of mine were satisfactory. Yours worked perfectly! Thank you again.

    …Eric

  19. Brent Says:

    Hey thanks for the cookie class. A real time saver.

  20. Greg Werner Says:

    Firefox it works great thank you. Unfortunately i am trying with 7 and 8 IE, and I have to see it work. I am trying to reach an average, non-net savvy, population who doesn’t know about flash settings, so maybe flash was a bad choice afterall.

  21. sheetal Says:

    Hey thanks for this article as well as library.Really helped me a lot.

  22. Balu Says:

    Hi!

    I have downloaded the cookie util but the “html-template” does not seem to work. I have tryed to open the “index.template.html” in explorer 7 and firefox 3. I only had some javascript error in ie7. Did not saved any cookies for me…

    What was my mistake?

    Thanks, Balu

    • kingschnulli Says:

      Did you even recompile that thing, I can show you like 1000 developers that are using it without problems – this is not made for people who are non flex developers.

  23. Mark Says:

    Added the following to your utility:

    private static var COOKIES_ENABLED:Boolean = false;

    public static function get enabled():Boolean
    {
    return COOKIES_ENABLED;
    }

    And place the following code in your init() function.

    //Test to see if cookies are enabled

    //Create a session cookie
    CookieUtil.create(“test”,”Success”,0);

    //Read the session cookie
    COOKIES_ENABLED = CookieUtil.read(“test”) == “Success”;

  24. Mike Says:

    Thanks for posting this. It’s quite nice and saved me a few hours of work.

  25. tgilders Says:

    One question I’m hoping there may be an easy answer for. What is the synax for retrieving a cookie that has a path structure defined? I can retrieve any cookie that is defined at root of the site, but any deeper than that I cannot get.

    Thanks in advance.

    • kingschnulli Says:

      That is quite easy, just change this block:

      private static const FUNCTION_SETCOOKIE:String =
      "document.insertScript = function ()" +
      "{ " +
      "if (document.snw_setCookie==null)" +
      "{" +
      "snw_setCookie = function (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+'; path=/';" +
      "}" +
      "}" +
      "}";

      to set a different path than “/”:

      private static const FUNCTION_SETCOOKIE:String =
      "document.insertScript = function ()" +
      "{ " +
      "if (document.snw_setCookie==null)" +
      "{" +
      "snw_setCookie = function (name, value, days, path)" +
      "{" +
      "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+'; path="+path+"';" +
      "}" +
      "}" +
      "}";

      and change this here:

      public static function setCookie(name:String, value:Object, days:int):void{
      if(!INITIALIZED)
      init();

      ExternalInterface.call("snw_setCookie", name, value, days);
      }

      to that:

      public static function setCookie(name:String, value:Object, days:int, path:String):void{
      if(!INITIALIZED)
      init();

      ExternalInterface.call("snw_setCookie", name, value, days, path);
      }

      do the same thing for the getter functions in there to also retrieve them from another path setting.

  26. Justin Says:

    great info! this saves me alot of time!

  27. Mike Says:

    I’m a little new to this so please forgive the basic question. I’m writing an air app which requires and HTTP POST login to a site, upon authentication a cookie is set. I’m a little confused as to where in my code I’d be placing the get / set portion. I’m creating a pop up window to do the login so I assume the code would be there or in the httpservice?

    • kingschnulli Says:

      I think you won’t need the cookie util for that purpose as the httpservice should take care of that set-cookie header. If not, you have to read the response headers, lookup the cookie and write it to the client. Please be aware that I do not know if and how this works in an AIR application as the class injects some javascript code into the wrapper through externalinterface. Perhaps you should grab a copy of the excellent tool Charles – with this you can get much more insight into the data flow, I have bought a copy myself and use it every day.

  28. Abdullah Says:

    Hello;
    Looks really handy, thanks for sharing this class.
    Is the third parameter of “setCookie” function in seconds or in minutes or in what?

  29. Andy Webb Says:

    Thanks! Works great and saved me from writing a similar one.


  30. Hi, Thanks for the code. Works great. I added a getAllCookies() method that returns all the cookies as an Object. Nothing too exciting, but, might save someone a few minutes if they need the same thing. — d
    You need to add the following methods…
    /**
    * Returns an object w/ each cookie as a property
    * Values will all be strings.
    */
    public static function getAllCookies():Object{
    if(!INITIALIZED)
    init();

    var allCookiesString : String =
    ExternalInterface.call(“snw_getAllCookies”) as String;
    var arr : Array = allCookiesString.split(‘;’);
    var o : Object = {};
    for each (var cookieString : String in arr) {
    var nameVal : Array = cookieString.split(‘=’);
    o[nameVal[0]] = nameVal[1];
    }
    return o;
    }
    private static const FUNCTION_GET_ALL_COOKIES:String =
    “document.insertScript = function ()” +
    “{ ” +
    “if (document.snw_getAllCookies==null)” +
    “{” +
    “snw_getAllCookies = function ()” +
    “{” +
    “return document.cookie;” +
    “}” +
    “}” +
    “}”;
    And change the following…
    private static function init():void{
    ExternalInterface.call(FUNCTION_GETCOOKIE);
    ExternalInterface.call(FUNCTION_SETCOOKIE);
    ExternalInterface.call(FUNCTION_GET_ALL_COOKIES);
    INITIALIZED = true;
    }


  31. Hey – sorry posted too soon. This works better (gets rid of leading space on cookie names).

    Hi, Thanks for the code. Works great. I added a getAllCookies() method that returns all the cookies as an Object. Nothing too exciting, but, might save someone a few minutes if they need the same thing. — d
    You need to add the following methods…
    /**
    * Returns an object w/ each cookie as a property
    * Values will all be strings.
    */
    public static function getAllCookies():Object{
    if(!INITIALIZED)
    init();

    var allCookiesString : String =
    ExternalInterface.call(”snw_getAllCookies”) as String;
    var arr : Array = allCookiesString.split(’;’);
    var o : Object = {};
    for each (var cookieString : String in arr) {
    var nameVal : Array = cookieString.split(‘=’);
    var name : String = nameVal[0];
    while (name.charAt(0)==’ ‘) name = name.substring(1,name.length);
    o[name] = nameVal[1];
    }
    return o;
    }
    private static const FUNCTION_GET_ALL_COOKIES:String =
    “document.insertScript = function ()” +
    “{ ” +
    “if (document.snw_getAllCookies==null)” +
    “{” +
    “snw_getAllCookies = function ()” +
    “{” +
    “return document.cookie;” +
    “}” +
    “}” +
    “}”;
    And change the following…
    private static function init():void{
    ExternalInterface.call(FUNCTION_GETCOOKIE);
    ExternalInterface.call(FUNCTION_SETCOOKIE);
    ExternalInterface.call(FUNCTION_GET_ALL_COOKIES);
    INITIALIZED = true;
    }

  32. vijaykrishna Says:

    Hi Thanks for Great Utility.
    Super smart code.

  33. mordsm Says:

    Hi,
    Does it works also on reading cookies that were set by a web site

    mordsm

  34. bob Says:

    I have question :
    There is swf(as2,as3,flex application) in an iframe, and iframe’s src is not same domain with the iframe parent’s url . How can I get the iframe parent’s url in swf.

    • kingschnulli Says:

      You have to allow scriptAccess for your flash movie, after doing so you might be able to get the parents url via javascript – if javascript allows this. If this is not possible you are not able to get this url without modifying the parents contents (setting cookies etc.)

      • Bob Says:

        but I can’t control the parents conent,it’s not my site,it ’s some site I don’t know.I just want to get domain which import my swf.

  35. jloa Says:

    But, why do u use cookies? SharedObjects are way much better. Why?

    1. Your class wont work if the allowScriptAccess is set to ‘never’, SharedObjects will still work.
    2. Cookies can be deleted via browser ‘Clear recent history’ option (e.g. FireFox ctrl+shift+del), SharedObjects – u cant delete that way.

    The verdict – use SharedObjects :)

    • kingschnulli Says:

      I already mentioned in another comment why I use Cookies, and what you point out as a contra point is a pro point for me (cookies can be deleted easily). Anyways, everybody should go for what he prefers.


  36. This is a nice post. Thank :D

  37. deepak Says:

    Hey thanks buddy….you did a really great job.

  38. Attila Says:

    Great work, man!
    I was trying to extract the session ID (JSESSIONID cookie) – this tool saved me a lot of headache.


Leave a Reply