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);
JavaScript is disabled in a WebView by default. You can enable it through the WebSettings attached to your WebView . You can retrieve WebSettings with getSettings() , then enable JavaScript with setJavaScriptEnabled() . WebView myWebView = (WebView) findViewById(R.
WebView allows you to bind JavaScript code to Android code through an interface. To do this, we must use the addJavaScriptInterface() method, which is passed the class that provides the interface for JS, and the name that will be used to display the instance in JS (for example, “AndroidFunction“).
Within the shouldOverrideUrlLoading() method simply get the URL from the request and pass into the Intent. See the full example.
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;
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With