How to use android webview for incognito tab?

593 Views Asked by At

I'm writing a light browser for my website and have to create incognito tab like chrome. I have used android webview. My problem is that when I use webview I can't save the cookies in a temporary location and delete the cookies file after the incognito tab is closed.
this is my code:

    CookieManager cookieManager = CookieManager.getInstance();
    if (this.isIncognito) {
        cookieManager.setAcceptCookie(false);
        webView.getSettings().setSaveFormData(false);
    } else {
        cookieManager.setAcceptCookie(true);
    }

how should I save cookies and delete it after closing tab?

1

There are 1 best solutions below

0
Vinay On

To launch a WebView in private mode in Android you have to clear all the history and cache stored by the webview.

        // init webview
        WebSettings webSettings = webView.getSettings();
        webSettings.setJavaScriptEnabled(true);

        // Enable private browsing mode
        webSettings.setCacheMode(WebSettings.LOAD_NO_CACHE);
        webSettings.setAppCacheEnabled(false);
        webSettings.setDomStorageEnabled(false);
        webSettings.setDatabaseEnabled(false);

        // Load a URL in the WebView
        webView.loadUrl("https://google.com");

and in onDestroy clear all stored cache and data by the webview.

@Override
    protected void onDestroy() {
        // Destroy WebView to free resources
        if (webView != null) {
            webView.clearHistory();
            webView.clearCache(true);
            webView.loadUrl("about:blank");
            webView.onPause();
            webView.removeAllViews();
            webView.destroyDrawingCache();
            webView.destroy();
        }
        super.onDestroy();
    }

or It is better to use Chrome Custom Tabs for opening URLs inside your app. Follow this link for more details https://developer.chrome.com/docs/android/custom-tabs/guide-get-started/