Skip to content

Instantly share code, notes, and snippets.

@zisismaras
Created May 8, 2016 14:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zisismaras/7624e73d422bfb2278298f859ce5722a to your computer and use it in GitHub Desktop.
Save zisismaras/7624e73d422bfb2278298f859ce5722a to your computer and use it in GitHub Desktop.
//our identifier to be added in front of the localstorage keys
var myId = "myIdentifier__"
//save the original functions
var _setItem = Storage.prototype.setItem;
var _getItem = Storage.prototype.getItem;
//overwrite their function bodys forcing javascript to create new function copies
Storage.prototype.getItem = function(item) {
//add the identifier infront of the key
item = myId + item
//and call the original function
return _getItem.call(this, item)
}
Storage.prototype.setItem = function(key, val) {
//add the identifier infront of the key
key = myId + key
//and call the original function
_setItem.call(this, key, val)
//return the value to comply with the standard behaviour
return val
}
//on reload we need to re-track our keys and re-define their getters
var watchList = {}
for (var prop in localStorage) {
//if it's not tracked
if(localStorage.hasOwnProperty(prop) && prop.indexOf(myId) > -1 && !watchList[prop]) {
//add it to the watchlist with its original key name
watchList[prop.replace(myId, "")] = localStorage[prop]
//define a custom getter that points to our modified getItem
Storage.prototype[prop.replace(myId, "")] = localStorage.getItem(prop.replace(myId, ""))
}
}
//dirty checking loop every 100ms
setInterval(function() {
for (var prop in localStorage) {
//if we have a new key or an existing key has an updated value
if(localStorage.hasOwnProperty(prop) && ((prop.indexOf(myId) === -1 && !watchList[prop]) || (prop.indexOf(myId) === -1 && watchList[prop] && localStorage[prop] !== watchList[prop]))) {
console.log("Saving " + prop + " = " + localStorage[prop] + " as " + myId + prop + " = " + localStorage[prop]);
//add it to the watchlist
watchList[prop] = localStorage[prop]
//use our modified setter to add it with an identifier on the front
localStorage.setItem(prop, watchList[prop])
//remove the original
localStorage.removeItem(prop)
//define a custom getter that points to our modified getItem
Storage.prototype[prop] = localStorage.getItem(prop)
}
}
}, 100)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment