Return to Snippet

Revision: 56143
at March 12, 2012 10:02 by EvanHahn


Initial Code
// Accessor: local('key')
// Setter: local('key', value)
// Destroyer: local('key', null)
Evan.local = function(key, value) {

	// Getter
	if (arguments.length === 1)
		return localStorage.getItem(key);

	// Clear it no matter what (for iOS)
	localStorage.removeItem(key);

	// Setter
	if (value !== null) {
		if ((typeof value !== 'string') && (!(value instanceof String)))
			value = JSON.stringify(value);
		localStorage.setItem(key, value);
	}

};

Initial URL


Initial Description
Here's how to use this:

* To access something in the local storage, type `Evan.local('name')`. You may need to use `JSON.parse()` on this result. Returns `null` if nothing's there.
* To assign something in the local storage, type `Evan.local('name', value)`.
* To remove something from the local storage, type `Evan.local('name', null)`.

This may not work if private browsing is enabled (eg, on Safari for iOS).

Initial Title
JavaScript local storage

Initial Tags
html5

Initial Language
JavaScript