Last active
August 9, 2017 10:59
-
-
Save eek/f7cf452edaab3eaea8dd2273ee700f75 to your computer and use it in GitHub Desktop.
localStorage Pollyfill for Safari / Chrome Private / Incognito Mode & Others
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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'); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
You should also add
to clean the
test
item