Handling cookies in PhoneGap/Cordova

Friend, I’ve tried too without success to use cookies with phonegap. The solution was use localStorage.

Key Quick Example:

 var keyName = window.localStorage.key(0);

Set Item Quick Example:

 window.localStorage.setItem("key", "value");

Get Item Quick Example

 var value = window.localStorage.getItem("key");
 // value is now equal to "value"

Remove Item Quick Example:

 window.localStorage.removeItem("key");

Clear Quick Example:

 window.localStorage.clear();

If you use you javascript for both mobile and web, you can use this code to detect that enviroment:

var wl = window.location.href;
var mob = (wl.indexOf("android")>0);

References:
http://docs.phonegap.com/en/1.2.0/phonegap_storage_storage.md.html#localStorage
http://cordova.apache.org/docs/en/6.x/cordova/storage/storage.html#page-toc-source

Be aware: using anonymous navigation on iOS may make localstorage not work like spected. A simple test that are working fine to me:

$(document).ready(function () {
    try {
        localStorage.setItem('test', '1');
    } catch (Err) {
        if (Err.message.indexOf('QuotaExceededError') > -1) {
            // Tell the user they are in anonymous mode
            // Sugest it to go to https://support.apple.com/pt-br/HT203036 to get help to disable it
            }
        }
    }
});

Leave a Comment