DEV Community

Code Green
Code Green

Posted on • Updated on

Android WebView: Handle special Intent URI requests

Background: When Developing a WebView based Android app, you might come across a scenario where the WebView Content/URL makes a special request to open an intent and the call fails.

Error: The Webpage at intent:/// could not be loaded because:
net::ERR_UNKNOWN_URL_SCHEME

Cause: The only reason behind this kind of failure is because WebViews are designed to handle only http: & https: protocols.

Solution: To handle special protocols like intent:, tel:, mailTo:
We need to embed a code to our WebViewClient and specify what steps to follow when such special protocols appear.

We need to override the shouldOverrideUrlLoading(WebView view, WebResourceRequest request) method from WebViewClient.

Note: You might get shouldOverrideUrlLoading(WebView view, String url) from you webViewClient, (this varies because of SDK version) but the below code will work for any of both methods.

Code:


               webView.setWebChromeClient(new WebChromeClient(){

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
                String url = request.getUrl().toString();
                if(url.startsWith("intent"))
                {
                    try {
                        Log.i(TAG,"inside intent starts with");

                        // let intnet handle this special protocol 
                        Intent intent = Intent.parseUri(url, Intent.URI_INTENT_SCHEME);
                        if (intent.resolveActivity(getActivity().getPackageManager()) != null) {
                            getActivity().startActivity(intent);
                            Log.i(TAG,"handled with intent parseUri");
                            return true;
                        }
                        //try to find fallback url
                        String fallbackUrl = intent.getStringExtra("browser_fallback_url");
                        if (fallbackUrl != null) {
                            webView.loadUrl(fallbackUrl);
                            Log.i(TAG,"handled with browser_fallback_url");
                            return true;
                        }

                    }  catch (Exception e) {
                       Log.e(TAG_ERROR, e);

                    }
                }

                // at the end if something fails, return the default method using super
                return super.shouldOverrideUrlLoading(view, request);
            }
        });
Enter fullscreen mode Exit fullscreen mode

Top comments (0)