WebViewClient not calling shouldOverrideUrlLoading

后端 未结 10 2354
逝去的感伤
逝去的感伤 2020-12-15 18:44

The problem is rather simple. In the application we want to keep track of the current url being displayed. For that we use shouldOverrideUrlLoading callback fr

10条回答
  •  清酒与你
    2020-12-15 19:23

    Another approach you can try: Catch the url by javascript side. Initialize your webView with this:

    webView.addJavascriptInterface(new WebAppInterface(getActivity()), "Android");
    

    After page is completely loaded (You can use an algorithm to check this like this https://stackoverflow.com/a/6199854/4198633), then:

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
        webView.evaluateJavascript("(function() {return window.location.href;})", new ValueCallback() {
            @Override
            public void onReceiveValue(String url) {
                //do your scheme with variable "url"
            }
        });
    } else {
        webView.loadUrl("javascript:Android.getURL(window.location.href);");
    }
    

    And declare your WebAppInterface:

    public class WebAppInterface {
        Activity mContext;
    
        public WebAppInterface(Activity c) {
            mContext = c;
        }
    
        @JavascriptInterface
        public void getURL(final String url) {
            mContext.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    //do your scheme with variable "url" in UIThread side. Over here you can call any method inside your activity/fragment
                }
            });
    
        }
    
    }
    

    You can do something like that to get url, or anything else inside the page.

提交回复
热议问题