Search code examples
androidxamarinwebviewxamarin.androidandroid-webview

How to catch all request in Webview - Xamarin


Am having a Webview in my Xamarin android project and am trying to Catch a URL with specific keyword. If the keyword is present I need to open that link through the normal browser.but the URLoverriding is not getting involked.

web_view.Settings.AllowFileAccessFromFileURLs = true;
        web_view.Settings.AllowFileAccess = true;
        web_view.Settings.JavaScriptEnabled = true;
        web_view.Settings.JavaScriptCanOpenWindowsAutomatically = true;
        web_view.Settings.DomStorageEnabled = true;
        web_view.Settings.DisplayZoomControls = true;
        web_view.Settings.SetSupportMultipleWindows(true);
        web_view.Settings.BuiltInZoomControls = true;
        web_view.LoadUrl(URL);
        web_view.SetWebViewClient(new HelloWebViewClient(this));

and this is my webview client

 public class HelloWebViewClient : WebViewClient
{

    public Activity mActivity;
    public HelloWebViewClient(Activity mActivity)
    {
        this.mActivity = mActivity;
                
    }

    public override bool ShouldOverrideUrlLoading(WebView view, IWebResourceRequest request)
    {
        string link = request.Url.ToString();
        if (link.Contains("Session"))
        {
            return true;

        }
        else
        {
            view.LoadUrl(request.Url.ToString());
            return false;
        }
        
    }

}

the URLOverride method is not getting involked, am I missing something? Please help.


Solution

  • Check shouldOverrideUrlLoading docs :

    Note: This method is not called for POST requests.

    Note: This method may be called for subframes and with non-HTTP(S) schemes; calling WebView#loadUrl(String) with such a URL will fail.

    In this scenaio , override ShouldInterceptRequest instead .

    Sample code

    public override WebResourceResponse ShouldInterceptRequest(WebView view, IWebResourceRequest request)
    {
        string link = request.Url.ToString();
        if (link.Contains("Session"))
        {
            return new WebResourceResponse("text/css", "UTF-8", data);
        }
        else
        {
            return base.ShouldInterceptRequest(view, request);
        }        
    }