Handling cookies in PhoneGap/Cordova

Bernd picture Bernd · Mar 11, 2013 · Viewed 76.1k times · Source

I'm working on a PhoneGap app with server session usage. It needs cookies to handle the session. Additionally, the cookie from the load balancer should be handled, too. So there is no way around. How do you handle Cookies in your PhoneGap app?

I have already accomplished some research:

  • Some say cookie handling might depend on the server not setting cookies for unknown user agents (IIS): PhoneGap session (cookies) on iOS
  • In JavaScript cookies can be set with document.cookie = ..., but they are not saved in PhoneGap and lost. Before firing xhr requests it works.
  • Cookies can be retrieved after xhr request with xhr.getResponseHeader('Set-Cookie'). But only when actually set on the server. Unfortunately, jQuery strips the "Cookie" header.
  • The JavaScript document.cookie property is not assigned and not updated after (xhr)requests.
  • Some suggest the localStorage to save session ids etc. But all scripts can access it and this might be XSS security issue. Cookies work around this issue by using the httponly flag.
  • iOS: There are some modifications which will change the webView behaviour to support cookies. But they seem not to work with iOS 6 and PhoneGap 2.5: https://groups.google.com/forum/?fromgroups=#!topic/phonegap/ZJE1nxX63ow
  • Cookies seem to be enabled by default in the AppDelegate.m (v2.5).

Answer

Tiago Gouvêa picture Tiago Gouvêa · May 15, 2013

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
            }
        }
    }
});