Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to listen for any cookie changes in Android Webview

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.

like image 737
Piyush Agarwal Avatar asked Oct 17 '22 14:10

Piyush Agarwal


2 Answers

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.

like image 50
Mark Avatar answered Oct 21 '22 07:10

Mark


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.

like image 36
amitfr Avatar answered Oct 21 '22 07:10

amitfr