Wednesday, October 26, 2011

How to read and write cookies with flash

After searching tones of pages on web I got disappointment that Flash is not having any capability to store something in cookie. Whenever I search for Flash cookies people always talks about ShareObject. I know ShareObject and I know there usage also. ShareObject is good when you want to store something in flash only and not any other application is going to read that data. 

Recently on my project Client asked me to read and write cookie through flash. First I did something with ShareObject but when more requirement come on this I felt ShareObject is not the right thing which I should use to store. Then I start searching about Cookie with flash but didn’t got any luck.

Finally I created this my own and now like to share with those who are looking for this solution for a long time.

HTML page with JavaScript

<script type="text/javascript">
 exLenght = 9
 exDate = new Date
 exDate.setMonth(exDate.getMonth()+exLenght)

function cookit() {
 for(i=0;i<cookit.arguments.length;i++) {
  ckThing = cookit.arguments[i] + '=' + cookit.arguments[i+1]
  i++
  document.cookie = ckThing + '; expires=' + exDate.toGMTString() + '; path=/'
  } 
 }

ckStr = "?"  
 if(document.cookie != "") {
  theCook = document.cookie.split("; ")
  for (i = 0; i < theCook.length; i ++) {
   ckStr += theCook[i] + "&"
   }
  }
</script>
this add swf Object in body to call swf on html page. 

<body>
<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="http://active.macromedia.com/flash2/cabs/swflash.cab#version=4,0,0,0" id="flookie" width="200" height="300">
    <param name="movie" value="flookies.swf?">
    <param name="quality" value="high">
    <param name="bgcolor" value="#99CC99">
    <embed src="flookies.swf" name="flookie" quality="high" bgcolor="#99CC99" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/shockwave/download/index.cgi?P1_Prod_Version=ShockwaveFlash" width="200" height="300">
    </object>
</body>

Now go to Flash and create one new document with 200x350 Action Script 1.0 create 2 input text field on stage and give var name as "name" and "txComment".
Also create 2 Buttons on stage one for "Write Cookie" and second one for "Read Cookie"
Your Flash File should looks like this.
Now write this code on "Write Cookie" Button
on (release)
{ 
  getURL("javascript:cookit(\'name\',\'" + /:name + "\',\'txComment\',\'" + /:txComment + "\')", "");
}
Now write this code on "Read Cookie" Button
on (release)
{
  getURL("javascript:if(document.cookie.length<1){alert(\'No cookie for%20this site.\')}else{alert(\'Your Cookie is:\'+document.cookie)}");
}
Now save your flash file as flookies.Fla and render .swf file
Note: you can choose any file name but make sure you use same swf name in html code also
Open you html page in IE and test also check yout Temporary Internet folder and fond the cookie.