html5 localStorage error with Safari: "QUOTA_EXCEEDED_ERR: DOM Exception 22: An attempt was made to add something to storage that exceeded the quota."

leiyonglin picture leiyonglin · Jan 28, 2013 · Viewed 146.3k times · Source

My webapp have javascript errors in ios safari private browsing:

JavaScript:error

undefined

QUOTA_EXCEEDED_ERR:DOM Exception 22:An attempt was made to add something to storage...

my code:

localStorage.setItem('test',1)

Answer

KingKongFrog picture KingKongFrog · Jan 28, 2013

Apparently this is by design. When Safari (OS X or iOS) is in private browsing mode, it appears as though localStorage is available, but trying to call setItem throws an exception.

store.js line 73
"QUOTA_EXCEEDED_ERR: DOM Exception 22: An attempt was made to add something to storage that exceeded the quota."

What happens is that the window object still exposes localStorage in the global namespace, but when you call setItem, this exception is thrown. Any calls to removeItem are ignored.

I believe the simplest fix (although I haven't tested this cross browser yet) would be to alter the function isLocalStorageNameSupported() to test that you can also set some value.

https://github.com/marcuswestin/store.js/issues/42

function isLocalStorageNameSupported() 
{
    var testKey = 'test', storage = window.sessionStorage;
    try 
    {
        storage.setItem(testKey, '1');
        storage.removeItem(testKey);
        return localStorageName in win && win[localStorageName];
    } 
    catch (error) 
    {
        return false;
    }
}