3

My application using a webview to open a webpage which is updating few cookies on some interactions taken on webpage. Now I want to read that cookie and make some UI tweaks based on the value of the cookie.

iOs has some implementation of Observers which can be attached to cookies list and get notifications for any cookie change happens.

I am searching similar solution from long but could not find any kind of listeners or something which can be attached to cookies and get to know when they are updated.

I read everything in CookieManager and CookieSyncManger

https://developer.android.com/reference/java/net/CookieManager.html

https://developer.android.com/reference/java/net/CookieManager.html

But nothing helpful.

I know using javascript interface hooks is a better solution but that can't be implemented for now as the website is already running in production.

pyus13
  • 24,402
  • 7
  • 94
  • 109

2 Answers2

2

I believe you need to go 1 layer deeper. A CookieStore - https://developer.android.com/reference/java/net/CookieStore.html is what you're looking for. You can create your own implementation overriding add(), get(), remove(), etc. and include your own callback there.

There's a SO post here that covers how to do that with a shared preferences backed implementation - How do I persist cookies when using HTTPUrlConnection?, but you can roll your own and back it however you want. (And yes, it's still relevant for Retrofit - Retrofit and persistent cookie store)

Sorry about that, same class name, different package - android.webkit.CookieManager not java.net.CookieManager. I took a look at the associated code for android.webkit.CookieManager & android.webkit.WebViewFactory.

The CookieManager is provided by the WebViewFactoryProvider instance. It does not appear to be possible to do what you desire without some serious hacking.

I also checked Crosswalk, which has an XwalkCookieManager. This might work for you, but it's not something I've tried, and it will drastically increase your APK size.

Community
  • 1
  • 1
Mark
  • 2,192
  • 16
  • 33
  • 1
    I tried it but it doesn't seem to work with webview cookies. CookieManager for webview is different than Http requests and There is no way I found to point my webview cookie manager to my own CookieStore . – pyus13 Apr 15 '17 at 04:32
  • Yup I went to the exact same path and found exact same thing yesterday. I had a lot of while opening the thread this morning but no luck. I am not a fan of hacks so thinking about to go and force the team to create a hook for me. Thank you so much for your help. – pyus13 Apr 17 '17 at 14:11
1

As a workaround, I read the cookies on every call to onLoadResource inside WebViewClient and compare it to previous values. This is more a busy loop than an observer pattern, but it works for me.

amitfr
  • 953
  • 1
  • 7
  • 25