For anyone interested, I ended up building a “localstorage with expirations” script here, http://plugins.jquery.com/project/localcache
What I’m doing: building an extension for Storage, so that the user can do this:
localStorage.setThing(key, value)
and the user can do the following:
localStorage.setThing("key1", 1)
localStorage.setThing("key2", "this is a string")
localStorage.setThing("key3", { prop1: "this is a json obj" })
In my setThing method, I’m checking for the typeof for value, and if typeof value == "object", I’m storing it as localStorage.setItem(key, JSON.stringify(value))
On the getThing method, I know that the value that makes it into localStorage is always going to be a string. So, how can I do this?
var val = localStorage.getItem("key3")
if (val is a previously JSON.stringify'd object) // <-- ??
return JSON.parse(val)
Do I need to do a regex check on val, and if so, does anyone have a pattern handy which tells me if a string is really a JSON.stringify’d object?
Thanks!
Another option is to store an object
{isJsonObj:true, jsonObj: jsonObj}, and check the type is Object, and isJsonObj is true. If either of those are false, then it isn’t a json obj (this means you don’t have to parse). I realise this means you won’t always have a string in there, but it makes it easy to test, and won’t carry a large amount of overhead.