Tuesday, June 23, 2009

Setting and Reading Cookies in Flash AS3

View actionscript 2 version of this post
Setting a cookie with Flash (Actionscript 3.0) is really easy. Reading that cookie in Flash (or passing the value of the cookie back into flash) isn't so easy (well, at least that's what the internet would have you believe). After searching for some documentation on the matter without any luck, I took matters into my own hands. It turns out if you use the jquery library, it is actually pretty easy.

First of all, you need to make sure you are using SWFobject to embed your flash, like this example: (make sure you have the swfobject js file included in your head)
<div id="flashcontent">Alt Content Goes Here</div>
<p><script type="text/javascript"> var so = new SWFObject("HomePageFlash.swf", "mymovie", "573", "434", "9", "#f0af2c");
  so.addParam("quality", "high");
  so.addParam("wmode", "transparent");
  so.write("flashcontent");
</script></p>


Then you need jquery installed.
And you also need the jquery cookie plugin included.

ACTIONSCRIPT:
To set a cookie from flash you just need to call a js function that is in the cookie plugin thusly:
var link:URLRequest = new URLRequest("javascript:$.cookie('flash_cookie', 'loaded')");
box_mc.addEventListener(MouseEvent.CLICK, onClick);
function onClick(event:MouseEvent):void{
  navigateToURL(link);

}
You can add as many params into the js call as you want thisly:
var link:URLRequest = new URLRequest("javascript:$.cookie('flash_cookie', 'the_value', { expires: 7, path: '/', domain: 'jquery.com', secure: true });");

Now for the exciting part. If you want to read that cookie in flash, all you need to do is pass it in using addVariables. In the SWFobject, just add this line of code BEFORE it writes the flash (so before the so.write part in my example):

  so.addVariable("theCookie", $.cookie('flash_cookie'));

('theCookie' being a variable that will be passed into flash and the $.cookie part will pull the value of that cookie and dump it into 'theCookie')
You probably know this already, but to read that variable in AS3, you need to call it like this:
myTextBox.text = this.loaderInfo.parameters.theCookie;
(that's to display it's value in a textfield called 'myTextBox', but you can do whatever you want with it)

If you have questions, feel free to comment.

(issues: Setting cookies in flash, reading cookies with flash, passing cookies into flash, as3, actionscript3, flash CS3, flash CS4, pass cookies with addVariables, pass cookies with SWFobject)