Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript "document.cookie" in Android?

I need help how to use correctly the javascript : "document.cookie" or how to write cookie from javascript in Android web browser ?

I've make sure in the settings that cookie is enabled. When I checked by using "navigator.cookieEnabled", it returns true as well.

I've a piece of javascript code as follow that has been working everywhere ( e.g. PC browsers, iPhone ), but doesn't work in Android.

function createCookie(name) {

// cookies expired in 1 year.

var expDate = new Date();

expDate.setDate(expDate.getDate() + 365);

expDate = expDate.toGMTString();

var el = document.getElementById(name);

document.cookie = name + '=' + escape(el.value) + '; path=/ ;expires=' + expDate;

document.cookie = name + '-idx=' + escape(el.selectedIndex) + ';path=/ ; expires=' + expDate;

//alert('cookie : ' + document.cookie);
}

When I open the 'alert' comment in the last line of code, Android will just show blank while all other browsers show me the content of the cookie that I've just written.

Please help. Thanks.

like image 958
Blingue Avatar asked Jul 26 '26 17:07

Blingue


1 Answers

I got this thing working, for Android 2.2, javascript's document.cookie works fine, just make sure that in your Webview...javascript is enabled like so:

yourWebViewVariable.getSettings().setJavaScriptEnabled(true);

for Android 3.1 just add this to your java file onLoadInit:

CookieManager.setAcceptFileSchemeCookies(true);   //This is the line that specifically makes it work so the other lines is optional

CookieManager cookieManager = CookieManager.getInstance();
cookieManager.setAcceptCookie(true);
cookieManager.acceptCookie();

Also, here's a few links that I found while I was trying to figure this error out, this could be helpful for others that wants to Send variables from Javascript to the Webview(Native Android Language) and Vise versa.

http://android-er.blogspot.com/2011/10/run-android-java-code-from-webpage.html

http://android-er.blogspot.com/2011/10/call-javascript-inside-webview-from.html

Thanks and Goodluck!

like image 86
redleome Avatar answered Jul 28 '26 05:07

redleome



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!