webChromeClient opens link in browser

冷暖自知 提交于 2019-11-28 21:21:07

WebChromeClient doesn't contain the shouldOverrideUrlLoading method, the WebViewClient does. Remember the "WebView" can and does use both WebViewClient and WebChromeClient at the same time if specified. The WebViewClient adds methods not available to you with no client assigned (keeping navigation in the webview). The same with the WebChromeClient has specific methods it can use (get page title on load for example).

So you can build your code like this:

WebView web = (WebView)findViewById(R.id.web);
WebSettings webSettings = web.getSettings();
webSettings.setJavaScriptEnabled(true);
webSettings.setGeolocationEnabled(true);
webSettings.setSupportMultipleWindows(true); // This forces ChromeClient enabled.    

web.setWebChromeClient(new WebChromeClient(){
    @Override
    public void onReceivedTitle(WebView view, String title) {
         getWindow().setTitle(title); //Set Activity tile to page title.
    }
});

web.setWebViewClient(new WebViewClient() {
    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
        view.loadUrl(url);
        return false;
    }
});

I was able to get around this by setting a dummy WebViewClient in addition to the WebChromeClient. Not sure why, but when I take out this line the web page starts opening in the browser again.

mBrowser.setWebViewClient(new WebViewClient());

To open links in the browser you can use an intent in the shouldOverrideUrlLoading method to launch the URL in a browser versus using your webview to handle the link:

webView.setWebViewClient(new WebViewClient(){
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
        if (url != null && url.startsWith("http://")) {
            view.getContext().startActivity(
                new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
            return true;
        } else {
            return false;
        }
    }
}

If you want to load in the webview use:

WebViewClient yourWebClient = new WebViewClient()
{
   // Override page so it's load on my view only
   @Override
   public boolean shouldOverrideUrlLoading(WebView  view, String  url)
   {
         // This line we let me load only pages with an anchor tag
         if ( url.contains("url") == true )
           //Load new URL Don't override URL Link
        return false;

   // Return true to override url loading (In this case do nothing).
   return true;
    }
};
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!