webChromeClient opens link in browser

Harry picture Harry · Feb 2, 2013 · Viewed 30.2k times · Source

I have searched and read a lot of posts but can not figure out how to do it in my code.

I want to use geolocation in my app and need to view in webChromeClient in stead of webViewClient which I use for the html files now and the links does stay in the same view.

When I change this to webChromeClient, the html links, like <a href="http://url/file.php?q=123", are suddenly opening in the browser!

How can I prevent this?

myWebView = new WebView(this);  
myWebView.getSettings().setJavaScriptEnabled(true);   
myWebView.getSettings().setLoadWithOverviewMode(true);
myWebView.getSettings().setUseWideViewPort(true);
myWebView.getSettings().setGeolocationEnabled(true);
myWebView.setWebChromeClient(new WebChromeClient() {
public void onGeolocationPermissionsShowPrompt(String origin, android.webkit.GeolocationPermissions.Callback callback) { 
        callback.invoke(origin, true, false); }
});
myWebView.loadUrl("file:///android_asset/HTML/index.html");
setContentView(myWebView);

Answer

Chad Adams picture Chad Adams · Apr 7, 2014

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