Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get Url of the WebView using WebResourceRequest in Java?

I have these codes:

   public class MyAppWebViewClient extends WebViewClient {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
            //want url of the webview in here
        }

I just want to know, how can I obtain the Url of the webView to override the Url loading. The shouldOverrideUrlLoading(WebView view, String url) method is depreceated in API21.

Thanks in advance!

like image 994
Pramesh Avatar asked Jun 07 '17 11:06

Pramesh


People also ask

How do I find my WebView URL?

String webUrl = webView. getUrl();

How do I import WebView?

Modify src/MainActivity. java file to add WebView code. Run the application and choose a running android device and install the application on it and verify the results. Following is the content of the modified main activity file src/MainActivity.

How do you override a WebView?

If you want to override certain methods, you have to create a custom WebView class which extends WebView . Also, when you are inflating the WebView , make sure you are casting it to the correct type which is CustomWebView . CustomWebView webView = (CustomWebView) findViewById(R. id.


1 Answers

boolean shouldOverrideUrlLoading (WebView view, String url) deprecated in API 24, boolean shouldOverrideUrlLoading (WebView view, WebResourceRequest request) added in API level 24

        @RequiresApi(api = Build.VERSION_CODES.N)
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
            if(Uri.parse(request.getUrl().toString()).getHost().endsWith("google.com")) {
                //The host application wants to leave the current WebView and handle the url itself. 
                return true;
            }

            if(Uri.parse(request.getUrl().toString()).getHost().endsWith("yandex.com")) {                    
                //The current WebView handles the url. 
                return false;
            }               

            if(Uri.parse(request.getUrl().toString()).getScheme().equals("file")) {
                //The current WebView handles the url. 
                return false;
            }

            Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(request.getUrl().toString()));
            view.getContext().startActivity(intent);
            return true;
        }
like image 152
Alexander Savin Avatar answered Nov 15 '22 12:11

Alexander Savin