简体   繁体   中英

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.

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.

\n

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM