Skip to content Skip to sidebar Skip to footer

Android Webview Cookie Returns Null

I'm trying to simply set and retrieve a cookie inside a webview in android. I have tried numerous cookie manager scripts to try and get this to work. I have JavaScript enabled. Wh

Solution 1:

After over a month of research I've concluded that setting a cookie in android versions greater than 2.3 is not possible in a webview where the file is on the localhost (read directly from the assets folder).

I went through many alternatives to to using cookie storage, including using HTML's localstorage. The whole issue here, I am led to believe, is security. If I were to create a cookie or localstorage on the localhost, then other apps could access that storage, thus is a major security threat.

My ultimate problem was trying to bridge the webview with two-way communication with java and also having a place to store data during the process. My solution was to take advantage of the JavascriptInterface

The idea is as follows:

  • Parse data to function in javascript
  • Javascript calls a special javascript function e.g. "setData(myDataName, myData)"
  • Java has a function which listens to this, and will take arguments set by javscript, and can also return values to javascript.
  • Once data is parsed to Java, java stores this in a series of files in assets.
  • When javascript function "getData(myDataName)" is called, the data is returned by the same kind of method by Java.

I found this very useful: Android JavascriptInterface Documentation, Handling JavascriptInterface in Android 2.3

The only major 'hang-ups' come with a what I found was a fairly serious bug in Android 2.3 (fixed in 3.0) which effectively broke the JavascriptInterface. The second link above describes the best workaround I have found.

Here is an example of how to get the two-way communication working (it's very messy, but it works):

Custom webinterface class:

public class webViewInterface { 
    //@JavascriptInterface //for SDK 12+
    public String showToast(String myText) {
        Toast.makeText(context, myText, Toast.LENGTH_LONG).show();
        return myText;
    }
    }

Main class: protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

engine = (WebView) findViewById(R.id.web_engine); 

context = this;
WebSettings webSettings = engine.getSettings();
webSettings.setJavaScriptEnabled(true);

engine.setWebViewClient(new WebViewClient());
engine.loadUrl("file:///android_asset/" + page);

boolean javascriptInterfaceBroken = false;
try {
        if (Build.VERSION.RELEASE.startsWith("2.3")) {
         javascriptInterfaceBroken = true;
        }
    } catch (Exception e) {

    // Ignore, and assume user javascript interface is working correctly.
    }

// Add javascript interface only if it's not broken
    // @TODO: write the workaround for < 2.3 devices
if (!javascriptInterfaceBroken) {
        engine.addJavascriptInterface(new webViewInterface(), "MainActivityInterface");
}   

//disables text selection
engine.setOnLongClickListener(new View.OnLongClickListener() {
    public boolean onLongClick(View v) {
        return true;
    }
});     
}

HTML:

<html>
<head>
</head>
<body>

<input type="button" value="Say hello" onClick="showAndroidToast();" />

<script type="text/javascript">
    function showAndroidToast() {
        document.write(MainActivityInterface.showToast("eureka!"));
    }
</script>

</body>
</html>

Solution 2:

I encountered the same limitations. I am loading local html files from the assets fodler. On a 2.2 emulator, cookies are stored and can be retrieved via JavaScript. However, testing on my 4.1 device, cookies set by a local page won't persist.

Based on @kirgy's and @user3220983's suggestions, I made it using the Javascript interface.

webview.addJavascriptInterface(new JavaScriptInterface(this), "Android");

public class JavaScriptInterface {         
    ...

    @JavascriptInterface
    public void setCookie(String name, String value) {
        Editor editor = activity.settings.edit();       
        editor.putString(name, value);
        editor.commit();
    }

    @JavascriptInterface
    public String getCookie(String name) {
        return activity.settings.getString(name, "");
    }   

    @JavascriptInterface
    public void deleteCookie(String name) {
        Editor editor = activity.settings.edit();       
        editor.remove(name);
        editor.commit();
    }

Note: these functions does not provide full cookie functionality (expiration, path), I am posting this as an idea of a good starting point.


Solution 3:

I encountered the same issue as kirgy. I was trying to use cookies (with javascript) in a Droid webview that displayed local content. It would not store the data. The same code worked perfectly if run from a remote url in the same webview though. Enabling cookies in java (with the Android CookieManger) had no effect.

Fortunately, I used custom javascript functions to encapsulate all my cookie needs in the local web app. Using the webview javascript interface, when running on the droid I just managed my cookies in a virtual manner by handling it up in the java.

For my needs, I only required session storage, so just put the cookies data in a java HashMap. I didn't worry about expiration dates or long term storage. If you need your "virtual cookies" to implement those details, it shouldn't be too difficult to figure out once the data is going to and from java via the js interface.


Post a Comment for "Android Webview Cookie Returns Null"