Pramesh
Pramesh

Reputation: 151

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!

Upvotes: 13

Views: 14822

Answers (3)

berdancan96
berdancan96

Reputation: 11

private String cUrl = "";

cUrl = webView.getUrl();

Then you can use it wherever you want.

Upvotes: 1

Alexander Savin
Alexander Savin

Reputation: 2012

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;
        }

Upvotes: 10

bjh
bjh

Reputation: 111

in \Android\sdk\sources\android-25\android\webkit\WebViewClient.java, you can see this code.

So short answer to your question is: request.getUrl().toString()

Check sources on GrepCode.

Upvotes: 10

Related Questions