appcelerator/titanium_mobile — pull request #719 by jeffbcross (2011-11-16 21:58:45+00:00)
Title: Implemented XHR/Webview Cookie Syncing in Android

I made a couple of changes to improve cookie handling in the SDK.
1. I exposed the new clearCookies method on iOS and Android to the Javascript API
2. I implemented the Android CookieManager with HTTPClient to share cookies from HTTPClient with the WebView, but not vice versa yet.

To use the test case:
1. Copy the code below into a new project's app.js
2. Launch in iOS or Android
3. Open the 2nd tab to see a webview, which should contain a message that no cookies were set.
4. Go back to the first tab and click the button titled "Set cookies over AJAX"
5. Wait a moment for request to post, and return to 2nd tab and click "Refresh" button near the top. The page should now indicate that a cookie called "TitaniumTestCookie" has been set.
6. Go back to the first tab and click the button called "Clear cookies"
7. Go to the 2nd tab and refresh the webView again. The body of the document should indicate that no cookies were set.

App.js:

Titanium.UI.setBackgroundColor('#000');
var tabGroup = Titanium.UI.createTabGroup();

var xhr = Ti.Network.createHTTPClient({
onload: function (e) {
Titanium.UI.createAlertDialog({
title: 'AJAX Complete',
message: 'Cookie should be set.',
buttonNames: ['OK']
}).show();
}
})

var win1 = Titanium.UI.createWindow({
title:'Control Cookies',
backgroundColor:'#fff'
});
var tab1 = Titanium.UI.createTab({
icon:'KS_nav_views.png',
title:'Set & Clear',
window:win1
});

var ajaxBtn = Ti.UI.createButton({
title: "Set cookies over ajax",
top: 10,
height:40
});

ajaxBtn.addEventListener("click", function (e) {
xhr.open("POST", "http://www.html-kit.com/tools/cookietester/");
xhr.send({
cn: "TitaniumTestCookie",
cv: "CookieValue"
});
});

win1.add(ajaxBtn);

var clearCookiesBtn = Ti.UI.createButton({
top: 60,
height: 40,
title: "Clear cookies"
});
clearCookiesBtn.addEventListener("click", function (e) {
xhr.clearCookies("http://www.html-kit.com");
Titanium.UI.createAlertDialog({
title: 'Cookies Clear',
message: 'Cookie have been cleared.',
buttonNames: ['OK']
}).show();
});

win1.add(clearCookiesBtn);

var win2 = Titanium.UI.createWindow({
title:'Test WebView',
backgroundColor:'#fff'
});
var tab2 = Titanium.UI.createTab({
icon:'KS_nav_ui.png',
title:'Test',
window:win2
});

var refreshBtn = Ti.UI.createButton({
title: "Refresh",
height:40,
top:0
});

var webView = Ti.UI.createWebView({
top: 40,
url: "http://www.html-kit.com/tools/cookietester/"
});

win2.add(webView);
win2.add(refreshBtn);

refreshBtn.addEventListener("click", function (e) {
if (Ti.Platform.osname === "android") {
webView.reload();
}
else {
webView.url = "http://www.html-kit.com/tools/cookietester/";
}
});

tabGroup.addTab(tab1);
tabGroup.addTab(tab2);
tabGroup.open();