Handling cookies in Android webview
I wrote the following html file
<code>
<html>
<head>
<script text ="text/javascript">
function createCookie(name,value,days) {
if (days) {
var date = new Date();
date.setTime(date.getTime()+(days*24*60*60*1000));
var expires = "; expires="+date.toGMTString();
}
else var expires = "";
开发者_如何学编程 document.cookie = name+"="+value+expires+"; path=/";
}
function readCookie(name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for(var i=0;i < ca.length;i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1,c.length);
if (c.indexOf(nameEQ) == 0) return(c.substring(nameEQ.length,c.length));
}
return null;
}
function modifyCookie() {
var newsessid = document.getElementById('userid').value;
//var oldsessid = document.getElementById('userid').value;
if(newsessid != "") {
eraseCookie('session id') ;
createCookie('session id', newsessid, 1);
//alert(readCookie('session id'));
document.getElementById('cookies').innerHTML = readCookie('session id');
return true;
}
//.value = readCookie('session id');
}
function eraseCookie(name) {
createCookie(name,"",-1);
}
function fillTextBox() {
//alert("Running");
document.getElementById('cookies').innerHTML = readCookie('session id');
document.getElementById('userId').value = document.getElementById('sessid').value;
}
</script>
<head>
<body onload="fillTextBox()" style = "height : 480px; width : 320px; background-image : url('investmentbanking/background2.png'); background-repeat : no-repeat">
<div style = "position : absolute; left = 80px; top = 160px;">
<label style = "color : #ffffff;">Session Id :</label>
<input type="text" id="userid" name="session"/>
<br/><br/>
<input type="hidden" id ="sessid" name="user" value="truce"/>
<input type="button" onclick="modifyCookie()" value="Modify Cookie" />
<br/>
<label>Stored Cookies : <label/><label id = "cookies"/>
</div>
</body>
</html>
</code>
When i open this file with my webview in android, and modify the content of the text box, and hit the modify cookie button, the text beside the "Cookies" doesn't get changed. The code works properly on Firefox and IE in the desktop, but not here... what could be the problem???
You must initialize a CookieSyncManager
instance tied to the app. Here is mine:
final Context myApp = this;
CookieSyncManager.createInstance(myApp);
CookieSyncManager.getInstance().sync();
Simply add this to the OnCreate()
method of the activity which loads the webview.
精彩评论