0
votes

I am struggling with using cookie along with javascript in webview android.

I have one HTML page which is located in sdcard data. This html file consist of javasript and cookie. I need to load this html file in webview and webview needs to respond to javascript as well as cookie.

Work done so far:-

Enabled javascript for webview

WebView1.getSettings().setJavaScriptEnabled(true);

Also tried to enable cookie using CookieManager

CookieManager.getInstance().setAcceptCookie(true);

Doing this, webview respond to javascript but not cookies. Any Idea how to solve this problem?

HTML file is as follows

<!DOCTYPE html>
<html>
    <head>
        <script>
            function setCookie(cname, cvalue, exdays) {
                    var d = new Date();
                    d.setTime(d.getTime() + (exdays*24*60*60*1000));
                    var expires = "expires="+d.toUTCString();
                    document.cookie = cname + "=" + cvalue + "; " + expires;
            }

            function getCookie(cname) {
                var res = "No Cookie!";
                    var name = cname + "=";
                    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);
                        if (c.indexOf(name) != -1) res = c.substring(name.length, c.length);
                    }
                document.getElementById('txt').innerHTML = res;
            }
        </script><noscript>No JavaScript!</noscript>
    </head>

    <body onload="setCookie('id', 'Cookie is working properly!', '1');">        
        <p id="txt"> </p>
        <center>
            <a href="./test-2.html">Next Page</a>
        </center>
    </body>
</html>

When i open this File in browser, its working fine. If someone wants to open this file in browser then please use the following url https://www.ypsid.com/demo/test/test-1.html

1
do you have write external storage permission in your android manifest file ? - Akhil
Yes its declared in menifest file.Html file is loaded in webview. There is no problem in opening html file in webview. The problem is webview is not responding to cookie - user3296352
Can you share your WebView codes? - ivan.sim

1 Answers

0
votes

If you are using Android Lollipop i.e. SDK 21, then:

CookieManager.getInstance().setAcceptCookie(true);

won't work. You need to use:

CookieManager.getInstance().setAcceptThirdPartyCookies(true);

I ran into same issue and the above line worked as a charm.