Tuesday, June 23, 2009

Setting and Reading Cookies in Flash AS2

View the actionscript 3 version of this post
Setting a cookie with Flash (Actionscript 2.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");

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

To set a cookie from flash you just need to call a js function that is in the cookie plugin thusly:
getURL("javascript:$.cookie('flash_cookie', 'the_value')");
You can add as many params as you need thisly:
getURL("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')

If you have questions, feel free to comment.

(issues: Setting cookies in flash, reading cookies with flash, passing cookies into flash, as2, actionscript2, flash 8, pass cookies with addVariables, pass cookies with SWFobject)