Thought I would share this hack.
The problem - you want to maintain some state on the client, but you don’t want to send this state on a pointless round-trip to the server with every request, as typically happens with Cookies.
There is a way around this though!
- add an hidden iframe to your page, with src=”/client-side-cookie/blank.html”
- from this directory, you serve a static empty HTML file, and, crucially, you serve this with Expires headers way into the future (see this Yahoo tip for some info about this technique)
- This file will not (typically) be re-requested before the time given in your Expire header
- Set cookies for the document in the iframe from your javascript code, with path=/client-side-cookie/, and with whatever expiry time you like. eg, iframe.contentDocument.cookie = ‘test=long_data_which_we_dont_want_to_send_to_the_server; path=/client-side-cookie/’
- When you want the data back in future - again, create the iframe (the HTML file will NOT be loaded from the server because of the Expires header, and so no cookies will be sent to the server). Then inspect iframe.contentDocument.cookie to get the data.
- Because you have restricted the path of the cookie, it will never be sent with requests for files outside of your special /client-side-cookie/ directory.
- Profit!
Problems:
- This can’t be relied on for security or privacy purposes not to send the data to server. The user could purge their browser cache, do a hard refresh on the file, etc.
- Even a far-future Expires header will expire eventually - and browsers may limit the length of Expires headers.
- So you should be prepared for the event that this data might, albeit very infrequently, get sent to the server.
- You are still limited to approx 4k per cookie (including key and value - google for detail on precisely what is supported cross-browser but it is at least very close to 4k)
- You are limited to 20 cookies per domain (in older IE versions at least, others allow more)
- So that caps it overall at about 80k, with some fiddling around to distribute the data between 20 separate cookies. Still, not to be sneezed at!
0 Responses to “80k of client-side-only storage for javascript, without browser extensions”
Leave a Reply
You must login to post a comment.