Skip to content

Instantly share code, notes, and snippets.

@eek
Last active August 9, 2017 10:59
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save eek/f7cf452edaab3eaea8dd2273ee700f75 to your computer and use it in GitHub Desktop.
Save eek/f7cf452edaab3eaea8dd2273ee700f75 to your computer and use it in GitHub Desktop.
localStorage Pollyfill for Safari / Chrome Private / Incognito Mode & Others
try {
localStorage.setItem('test', true);
} catch (e) {
if (e.code == 22) { //localStorage exists but size limit -> Probably Safari Private Mode.
localStorage.__proto__ = Object.create(Storage.prototype);
localStorage.__proto__._data = {};
localStorage.__proto__.setItem = function (id, val) {
return this._data[id] = String(val)
};
localStorage.__proto__.getItem = function (id) {
return this._data.hasOwnProperty(id) ? this._data[id] : undefined
};
localStorage.__proto__.removeItem = function (id) {
return delete this._data[id]
};
localStorage.__proto__.clear = function () {
return this._data = {}
};
}
} finally {
localStorage.removeItem('test');
}
@legraphista
Copy link

You should also add

try{<...>}
catch(e){<...>}
finally {
   localStorage.removeItem('test');
}

to clean the test item

@eek
Copy link
Author

eek commented Jun 26, 2016

Added, thanks! :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment