in Appcelerator Titanium

Get Cookies from a Webview in Titanium

I needed to fetch a value out of a cookie in a Titanium Webview for both iOS and Android. I had been using evalJS, but it recently broke on Android, so I was out of luck.  At the same time, Ti SDK 3.2 introduced Ti.Network.Cookie, but it appears to only be for Android, and I wanted to keep the code pretty similar for both platform, so here we are: titanium-cookies.

titanium-cookies uses CookieManager on Android, and NSHTTPCookieStorage on iOS to fetch the cookie for a given url. I suppose it could fetch any cookie in the app, but I used it to get cookies after loading a page in the webview.  The easiest way I have found to do this is listen for the webview load event, and then just pass the url in the event data on to getCookie(), like this:

var monster = require('com.polancomedia.cookies');

myWebview.addEventListener('load', function(e) {
    var url = e.url;

    Ti.API.info('fetch cookie for: ' + url);
    var cookies = monster.getCookie(url);

    for(var key in cookies){
        Ti.API.info('name: ' + key + ' value: ' + cookies[key]);
    }
});

Get the Module here.

Pretty simple! I haven’t really planned on adding any other methods for managing cookies or exposing any other cookie data, just because the need hasn’t yet come up, but feel free to post your desires and wishes (related to cookies, natch) on the repo, or better yet, fork and contribute!

OM NOM NOM.