23

I need to get all the cookies that are stored in the webview. Currently the default webview.

https://developer.android.com/reference/android/webkit/CookieManager.html

Currently it only supports:

  • getCookie(String url)

I need the ability to get all the cookies without knowing the exact domain name.

Any Advice Appreciated Thanks, D

darewreck
  • 2,576
  • 5
  • 42
  • 67

2 Answers2

2

In Java, as I understood you are using webView and you want to get all cookies of specific previewed URL, you can get current URL from webView client an pass it as a parameter to getCookie()

String cookies = CookieManager.getInstance().getCookie(webView.getUrl());

as a best practice, you should try it after page loaded like this

    WebView webView = findViewById(R.id.webview_id);
    WebViewClient webViewClient = new WebViewClient(){
        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
            String cookies = CookieManager.getInstance().getCookie(view.getUrl());
            // save cookies or call new fun to handle actions 
            //  newCookies(cookies);
        }
    };
    webView.setWebViewClient(webViewClient);
    //webView.loadUrl(/*what ever url you want to load */);
0

You can create your own cookie storage and intercept cookies loaded by the WebView. Example using java.net.CookieManager as storage:

val cookieManager = java.net.CookieManager()

webView.webViewClient = object : WebViewClient() {
    override fun onPageFinished(view: WebView?, url: String?) {
        CookieManager.getInstance()
                .getCookie(url)
                ?.let {
                    val uri = URI(url)
                    HttpCookie.parse(it).forEach {
                        cookieManager.cookieStore.add(uri, it)
                    }
                }
    }
}
SpaceBison
  • 2,525
  • 1
  • 21
  • 38
  • 2
    Is it possible to intercept also third-party cookies with this? Moreover, what is the aim of the API `CookieStore.getCookies()` if it's not possible to use it? I really do not understand this Android design choice... – toioski Jul 25 '18 at 08:05
  • This will only save cookies for explicitly loaded urls, no resources loaded in the background will be handled actually. I'll try to post a better approach soon. – SpaceBison Jul 30 '18 at 05:38
  • A better approach would be using `shouldInterceptRequest()` callbacks to intercept all HTTP request and extract cookies while handling the requests yourself. I tried to write a working example, but because `WebResourceRequest` and `WebResourceResponse` interfaces are weird and require some tinkering to interoperate with `HttpUrlConnection` or even `OkHttpClient`, I failed miserably. Hopefully you'll have more luck with this idea. ;) – SpaceBison Jul 30 '18 at 06:54