4

I'm trying to set a cookie using javascript inside a webview. The webview is loaded from the local assets directory like so (where page is a string such as "index.html")

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

I have found when the exact same file is loaded from the web (i.e. http://www.domain.com/index.html) then same file can set the cookie as expected.

Older versions of android do allow the creation of cookies on local files, but newer versions do not. I have tested this and it works on Samsung Galaxy Ace, HTC Desire Z and eclipse emulators of lower SDK, but does not work on Samsung SIII nor Samsung Tab 10.1.

I need to set a cookie in order to carry data between pages in my webview; saving search results to be re-displayed.

If anyone knows of any methods/hacks to get around these local file problem I'd really reeeally appreciate it. I've been at this for about 8 weeks now. I asked a simular question which may be helpful for further reading, but the problem has now been identified and is very much a different question so I'm asking this here. Android webview cookie returns null

Thanks.

Community
  • 1
  • 1
kirgy
  • 1,567
  • 6
  • 23
  • 39
  • I know it is asked long time ago but have you found any solution yet? – Hamid Feb 03 '15 at 15:20
  • The problem is caused by a fix for security issue. Allowing any app to store cookies under the "localhost" domain. This effectively means that anyone could create an app to read/write from the same cookie store. As a result this was blocked by Android in later versions of Android. See my similar question: http://stackoverflow.com/questions/19235489/android-webview-cookie-returns-null – kirgy Feb 04 '15 at 09:14

2 Answers2

1

The reason this is not possible is down to a security limitation of implementing cookies over localhost. If cookie setting were possible, then it would also be possible for others to create apps and read your apps cookies. It used to be possible on early versions of Android, but the security hole was later patched.

This is why the same limitation exists on conventional web browsers.

See this related question and answer: Android webview cookie returns null

Community
  • 1
  • 1
kirgy
  • 1,567
  • 6
  • 23
  • 39
0

I've been dealing with a similar use case like the one you describe, here's the approach I took

  • Whenever I needed to set cookies directly on the Cordova WebView (like file scheme cookies):

    CookieManager.getInstance().setCookie("/", "MyCookie=xxx");
    
  • When a JS library would create file scheme cookies (since they are loaded from the file system) and I needed to fetch those values on the "native" layer, I would use:

    CookieManager.getInstance().getCookie("file://");
    

The latter would return a long string of all the file scheme cookies, which you can split into an array and parse one by one

Hope this helps.

Pepe Ramirez
  • 387
  • 4
  • 15