Actionscript Cookie Util


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.

Edit:

Wow, I can’t believe how many people claim this as their own code – I’m not complaining but just renaming or removing the package name isn’t enough for a cheap copy 🙂 Here are some examples (my js functions name starts with ‘snw_’ – this is our shirtnetwork prefix so this is quite funny to see):

http://code.google.com/p/goodboyxmeangirl/source/browse/trunk/railk/as3/utils/CookieUtil.as (he dropped a comment, so everything fine here now)

http://workingsoftwaresolutions.blogspot.com/2010/01/cookie-setting-in-flex-actionscript.html (added link to this post, changed package name – no problem)

http://www.imemment.com/post/86.html

And here is one I like, he links to this post and he didn’t rename the package to claim it as his own (at least i think that):

http://blog.jidolstar.com/454?t=c&i=0

Guys if you take the util this is fine, but if you just rename the package and put it onto your page without a backlink this sucks .

  1. 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. 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.

    • Aran
    • November 14th, 2008

    “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?

  3. 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 ?

    • Russ
    • November 14th, 2008

    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.

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

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

    • reinhard
    • November 19th, 2008

    download is not working

  6. 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.

    • Charlie
    • November 25th, 2008

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

    • Hari
    • December 2nd, 2008

    Hi,
    Thanks a lot for this post.

    Really fantastic stuff. Great man

    Regards

    • Sjoedzj
    • December 3rd, 2008

    Nice One

  7. Thanks for this, saved my arse today!

    • Tommy
    • January 22nd, 2009

    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

    • 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.

    • Abdul Areef
    • February 5th, 2009

    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

    • 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.

  8. 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?

    • 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 ?

  9. 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

  10. Thanks!

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

  12. 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.

    • sheetal
    • April 2nd, 2009

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

    • Balu
    • April 24th, 2009

    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

    • 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.

    • Mark
    • April 28th, 2009

    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”;

    • Mike
    • April 30th, 2009

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

    • tgilders
    • May 13th, 2009

    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.

    • 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.

        • Denver
        • October 25th, 2011

        Hi,

        I am trying to edit the getter functions as you mention here in order to access a cookie that is not at the top level. I can’t seem to get the edits right though, so I was wondering if you could post the getter function code here that would allow for a path parameter? Thanks in advance.

  13. great info! this saves me alot of time!

    • Mike
    • June 17th, 2009

    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?

    • 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.

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

    • it is in seconds i think, it is the same measure you have in the javascript function.

    • Andy Webb
    • June 26th, 2009

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

  15. 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;
    }

  16. 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;
    }

    • Thanks for the addition, I just checked your blog some days ago – nice things up there 😉

    • vijaykrishna
    • July 27th, 2009

    Hi Thanks for Great Utility.
    Super smart code.

    • mordsm
    • July 30th, 2009

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

    mordsm

    • Sure, you can read any cookie you can read in the html wrapper – so all cookies set on this domain.

  17. 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.

    • 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
        • August 31st, 2009

        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.

  18. 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 🙂

    • 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.

  19. This is a nice post. Thank 😀

    • deepak
    • November 2nd, 2009

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

    • Attila
    • November 16th, 2009

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

    • Yuval
    • December 8th, 2009

    The example doesn’t work for me in Firefox, only IE…
    Any ideas?

    On Firefox I get:
    [SWF] F:\metronet\projects\partypop\CookieTester\bin-debug\CookieTester.swf – 708,452 bytes after decompression
    SecurityError: Error #2060: Security sandbox violation: ExternalInterface caller file:///F:/metronet/projects/partypop/CookieTester/bin-debug/CookieTester.swf cannot access file:///F:/metronet/projects/partypop/CookieTester/bin-debug/CookieTester.html.
    at flash.external::ExternalInterface$/_initJS()
    at flash.external::ExternalInterface$/call()
    at de.aggro.utils::CookieUtil$/init()[F:\metronet\projects\partypop\CookieTester\src\de\aggro\utils\CookieUtil.as:52]
    at de.aggro.utils::CookieUtil$/setCookie()[F:\metronet\projects\partypop\CookieTester\src\de\aggro\utils\CookieUtil.as:59]
    at CookieTester/___CookieTester_Button1_buttonDown()[F:\metronet\projects\partypop\CookieTester\src\CookieTester.mxml:16]
    at flash.events::EventDispatcher/dispatchEventFunction()
    at flash.events::EventDispatcher/dispatchEvent()
    at mx.core::UIComponent/dispatchEvent()[C:\autobuild\3.2.0\frameworks\projects\framework\src\mx\core\UIComponent.as:9298]
    at mx.controls::Button/http://www.adobe.com/2006/flex/mx/internal::buttonPressed()[C:\autobuild\3.2.0\frameworks\projects\framework\src\mx\controls\Button.as:2504]
    at mx.controls::Button/mouseDownHandler()[C:\autobuild\3.2.0\frameworks\projects\framework\src\mx\controls\Button.as:2750]

    • You need to give allowScriptAccess=”sameDomain” at least to get the cookie util working on a page, check google for allowScriptAccess.

        • alper
        • January 26th, 2011

        I have problem in flex cookie it works nice in internet explorer but don’t work in firefox are any one have solution to that

        thanks
        alper

    • Ragu
    • January 11th, 2010

    Really great. Nice Post.
    I am going to integrate with my Flex App.
    Thanks for sharing with us.

    • KrisB
    • January 12th, 2010

    This is exactly what i was looking for.
    However i can’t get it to work in IE. Is there somting other than the “allowScriptAccess” setting that i should be looking at.
    It works superbly i FireFox and Safari.

    • I am quite sure that your problem is some kind of Flash Player Sandbox issue. Are you using swfobject or AC_OETAGS to embed the movie or just a plain construct? If you are using the method you will have to set the allowScriptAccess at 2 places (once for FF, once for IE). You might also just check if any errors are thrown (i.e. upload the debug movie and use a debug player). I am using this successfully in a lot of environments, never had any problems.

        • KrisB
        • January 13th, 2010

        I have been testing and it seems that in IE i can’t write and can’t read the cookies. (FF and Safari are OK)

        My HTML code look’s like:

        AC_FL_RunContent( ‘codebase’,’http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,28,0′,’width’,’200′,’height’,’200′,’src’,’/_swf/globvar’,’quality’,’high’,’pluginspage’,’http://www.adobe.com/shockwave/download/download.cgi?P1_Prod_Version=ShockwaveFlash’,’movie’,’/_swf/globvar’,’allowScriptAccess’,’always’ ); //end AC code

        Can you see somthing wrong here?

      • Hmm, I wouldn’t recommend using that AC_FL_RunContent tag – but that’s a different story (go and check swfobject). What is the generated markup that you recieve? I mean the code that is being generated by AC_FL ?

        • KrisB
        • January 14th, 2010

        Thanks!

        I looked at the SwfObject 2.2 and it now works in IE.

  20. NICE!!!
    It’s works fine!

    Thanks from Italy!

    Marco

    • Krishna
    • February 5th, 2010

    Great work man.
    Being a newbie flex i am very much satisfied with this thank you.

    • Faruq Shaik
    • April 27th, 2010

    I am getting below error:

    Implicit coercion of a value with static type Object to a possibly unrelated type String

    can anybody provide whats the problem here?

    Thanks in advance

    • Sebastian
    • July 14th, 2010

    This seems to be exactly what I need, however “Deposit Files”has been telling me for a couple of days:

    Dear clients,
    we re sorry but at the moment this file is not available for downloading due to software renovations.
    We guarantee it will become available after some period of time.
    Please try later.

    Could you send me the file per Email?

    Thanks, Sebastian

    • Sebastian
    • July 14th, 2010

    Download problem: Deposit Files keeps saying:

    Dear clients,
    we re sorry but at the moment this file is not available for downloading due to software renovations.
    We guarantee it will become available after some period of time.
    Please try later.

    Could you send me the file per Email?

    Thanks, Sebastian

    • Sebastian
    • July 15th, 2010

    The download page is still not functional. I am not sure it is a temporary thing. Could you please sort something out for me? Email, or whatever. I’d be very thankful, this seems just the thing I need!

    • zubin shi
    • July 26th, 2010

    This looks interesting. Unfortunately it seems the link doesn’t work anymore. Would you mind to send the codes via email to me.

    Thanks

      • zubin shi
      • July 26th, 2010

      acutally I am getting this error when try to download it:

      Dear clients,
      we re sorry but at the moment this file is not available for downloading due to software renovations.
      We guarantee it will become available after some period of time.

  21. Bedava Her şey burda

  22. Thanks teşekkürler

  23. Thanks for writing this great AS Cookie Utility. We are happy to tell you that we are starting to use it across IXTROM applications.

    Thanks !

  24. Hy!

    When I login with my flex app and then I want to get the cookie of the session it returns null. But if I set with flex another var and the I get it back it works.

    The cookie name is “DgU00” and I do like this:
    var SID:* = CookieUtil.getCookie(‘DgU00’);
    and SID = null
    if I do:
    CookieUtil.setCookie(‘DgU01’, ‘abcd’, 4);
    var SID2:* = CookieUtil.getCookie(‘DgU00’);
    I get SID2 = ‘abcd’

    why?

    • you might have to use the domain patch that somebody posted in the thread to target the right domain.

    • railk
    • November 3rd, 2010

    Hello,

    I’m really sorry, there was no mention that it was your file, i usually keep all informations from the author of the class file if i didn’t wrote it myself (i put files in my own package for ease of use), i’ve put your name and link back to this post.
    Sorry again for that, i didn’t meant to make appear i wrote it. If you want me to delete it from my google account i will as its just a “save” repository for me.

    • never mind, i’m always glad if people even react on such things – so keep it wherever you want, just mention the origin 😉

    • james
    • December 7th, 2010

    Hi,

    thanks a lot for this, i’m hoping it can help me with an issue i have. I’m in the same position as the guy above, where i’m getting null returned. I’ve checked the comments and searched google, but can’t find the ‘domain patch’ thread you’re talking about?

    Is it your comment from May 19th 2009?

    Cheers.

  25. Thanks a lot! helped me tons! 🙂

    • Anthony
    • January 8th, 2011

    Hi,

    Thanks so much for this! I am able to read cookies with the get, but call the set, then the get again and nothing has changed. I’m running in IE and am attempting to reset a LptaToken cookie.

    Any thoughts?

    • alper
    • January 26th, 2011

    alper :
    Your comment is awaiting moderation.
    I have problem in flex cookie it works nice in internet explorer but don’t work in firefox are any one have solution to that
    thanks
    alper

    james :
    Hi,
    thanks a lot for this, i’m hoping it can help me with an issue i have. I’m in the same position as the guy above, where i’m getting null returned. I’ve checked the comments and searched google, but can’t find the ‘domain patch’ thread you’re talking about?
    Is it your comment from May 19th 2009?
    Cheers.

    • Attract
    • May 19th, 2011

    Hi..
    Reading Cookies and writing cookies from Flex does not work on Google Chrome. It works perfectly fine for IE and firefox. Any clue? has anyone tried on Chrome? Any help would be appreciated. Many Thanks!

    • Attract
    • May 20th, 2011

    Hi.. It works on google chrome as well.. I was testing it as an independant applicaiton file, and when I registered the cookie, it didnt have any domain. When I integrated it with the application, the cookie got domain info and Google Chrome registered the cookie. Thanks a lot!

    • Anand Meena
    • September 1st, 2011

    Hi,

    I am using a HTML bowser control in my adobe air applicaiton.
    That is work like a clone of IE browser.
    I want to remove all cookies of IE browser from my application.

    What should I do.

    Thanks in advance.

  26. any chance you might post this up on say google code or github? Would make forking and improving easier. If not, have you any objections to me posting this up on a repo? Of course all credits would link back to your site.

    • Sure, as long as you leave the credits intact you can take it and do whatever you want 🙂

  1. November 13th, 2008
  2. December 19th, 2008
  3. January 8th, 2009
  4. October 12th, 2009
  5. September 12th, 2010
  6. December 21st, 2010

Leave a reply to Mark Cancel reply