nachshon f
nachshon f

Reputation: 3670

Getting Security Error on iPhone when using localStorage

When I try saving anything with localStorage.setItem(""); in IOS Safari, I get this error -

SecurityError (DOM Exception 18): The operation is insecure.

Here is a screenshot of the error...

enter image description here

Any ideas how to fix this? Thanks.

Upvotes: 8

Views: 9405

Answers (3)

Sylwester Kogowski
Sylwester Kogowski

Reputation: 170

It's not only Safari, but also Firefox in private browsing mode. Chrome doesn't block localStorage in incognito mode, but it is being reset at each session (which is a better option imho). In either case, you shouldn't use localStorage directly, but instead make a script that uses it if it is available, and if not, then use sessionStorage. I.e.

var backupStorage = {};
var storageMode = 'localStorage';
try {
    localStorage.length;
} catch(e) {
    try {
        sessionStorage.length;
        storageMode = 'sessionStorage';
    } catch(e) {
        storageMode = 'backupStorage';
    }
}

function setLocalStorage(key, value) {
    switch(storageMode) {
        case 'localStorage':
            localStorage.setItem(key, value);
            break;
        case 'sessionStorage':
            sessionStorage.setItem(key, value);
            break;
        case 'backupStorage':
            backupStorage[key] = value;
            break;
    }
}
function getLocalStorage(key) {
    switch(storageMode) {
        case 'localStorage':
            return localStorage.getItem(key);
        case 'sessionStorage':
            return sessionStorage.getItem(key);
        case 'backupStorage':
            return backupStorage[key];
    }
}

Upvotes: 2

maracuja-juice
maracuja-juice

Reputation: 1042

I had this problem on the desktop version of Safari. I enabled "Disable Local File Restrictions" This is how you can find it:

where to find "disable local file restrictions" in desktop safari

Your cookie settings are also not allowed to be on "Always block". Otherwise you also get this error!

Upvotes: 4

nachshon f
nachshon f

Reputation: 3670

Found the answer. Block Cookies was turned on in the users Safari Settings.

Upvotes: 17

Related Questions