Friday, February 23, 2007

Cookies and Flash for local storage

In previous posts I provided code for using cookies in JavaScript. I've now enhanced that code to utilize the flash storage mechanism which was described by Christoph Khouri, however his page seems to be down currently, so I'll provide the files you need. Note: this is the same technique used by the Dojo Storage module, without the need for Dojo which adds extra overhead costs.

Using flash storage alleviates the 4k size limit of cookies and initially provides 100k of storage seamlessly and can be increased to any size by the user. It also eliminates unnecessary network traffic as all the cookies are transmitted to the server all the time, and makes it harder for prying eyes to see what's being stored as vs browsing the cookies in the browser.

In order to use the flash storage, first, download which came from Christoph Khouri's site. Next, download my current cookies.js file.

Now, include the flashStorage JavaScript and my cookies.js JavaScript in the header of your HTML page:

<script type="text/javascript" src="jscript/flashStorage/swfobject.js">lt;script>
<script type="text/javascript" src="jscript/flashStorage/flashStorage.js"><script>
<script type="text/javascript" src="jscript/cookies.js"></script>

Next, somewhere in the body your page add the following code:

<div style="float: right;" id="storageHolder">
<embed type="application/x-shockwave-flash"
src="jscript/flashStorage/storage.swf" id="storageMovie" name="storageMovie" bgcolor="#ffffff" quality="high"
swliveconnect="true" wmode="transparent" height="137" width="214" />
<script type="text/javascript">
var so = new SWFObject("jscript/flashStorage/storage.swf", "storageMovie", "50", "10", "8", "#ffffff");
so.addParam("swLiveConnect", "true");
so.addParam("wmode", "transparent");

//Initialize the flash storage by passing the id of the flash movie

That's it! Now whenever you create a cookie like Cookies.create("myCookie", "myValue") it will actually store that in the flash storage instead. However, if you don't wish to include the Flash storage component, it will default to store the value in a browser cookie instead.

Maybe sometime in the future I'll add detection to see if the Flash plugin is installed in addition to the Storage object and default to standard cookies if Flash isn't installed.
Update: I've added a check for the Flash plugin being installed as a pre-requisite to using the Flash storage object in addition to the check for the JavaScript code/object being included. FYI, my check for Flash for those needing to do the same thing is:

var hasFlash = (navigator.plugins &&
(navigator.plugins["Shockwave Flash"] || navigator.plugins["Shockwave Flash 2.0"])) ||
(navigator.mimeTypes &&

1 comment:

Anonymous said...

Thanks for the script. I would like to request the script to store and read a variable. Thanks.