Last active
May 1, 2023 12:43
-
-
Save juanparati/b0c41312d086752df154b738be6c8041 to your computer and use it in GitHub Desktop.
Avoid Session and Local storage quota error overriding the Storage prototype
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
/** | |
* Override Localstorage and Sessionstorage setItem prototype | |
*/ | |
Storage.prototype._setItem = Storage.prototype.setItem; | |
Storage.prototype.setItem = function(key, value) | |
{ | |
const isQuotaExceededError = (err: unknown) => err instanceof DOMException && | |
( | |
// Legacy Webkit | |
err.code === 22 || | |
// Legacy Gecko | |
err.code === 1014 || | |
// test name field too, because code might not be present | |
// everything except Firefox | |
err.name === "QuotaExceededError" || | |
// Gecko | |
err.name === "NS_ERROR_DOM_QUOTA_REACHED" | |
); | |
try { | |
this._setItem(key, value); | |
} catch (err) { | |
if (isQuotaExceededError(err)) { | |
console.warn(`Quota exceeded when attempting to write ${key} (Usage: ${this.length} keys)`); | |
this.clear(); | |
} | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment