【问题标题】:How to get Url of the WebView using WebResourceRequest in Java?如何在 Java 中使用 WebResourceRequest 获取 WebView 的 Url?
【发布时间】:2017-11-08 18:23:03
【问题描述】:

我有这些代码:

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

我只想知道,如何获取webView的Url来覆盖Url加载。 shouldOverrideUrlLoading(WebView view, String url) 方法在 API21 中已弃用。

提前致谢!

【问题讨论】:

    标签: java android android-studio webview


    【解决方案1】:

    boolean shouldOverrideUrlLoading (WebView view, String url) 在 API 24 中已弃用,boolean shouldOverrideUrlLoading (WebView view, WebResourceRequest request) 在 API 级别 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;
            }
    

    【讨论】:

    • 这应该是选择的答案。
    【解决方案2】:

    \Android\sdk\sources\android-25\android\webkit\WebViewClient.java中,可以看到这段代码。

    您的问题的简短回答是: request.getUrl().toString()

    查看GrepCode 上的来源。

    【讨论】:

    • 如果我使用低于 25 的 API 版本怎么办
    【解决方案3】:
    private String cUrl = "";
    
    cUrl = webView.getUrl();
    

    然后你可以在任何你想要的地方使用它。

    【讨论】:

      猜你喜欢
      • 2018-03-10
      • 1970-01-01
      • 1970-01-01
      • 2016-01-10
      • 1970-01-01
      • 1970-01-01
      • 2019-07-19
      • 2017-04-18
      • 1970-01-01
      相关资源
      最近更新 更多