I\'m using a WebView in my application, I have a requirement to change the app title based on the page user is on. How can I do this in Android WebView?
I did this i
So my experience you should use onReceivedTitle and onPageFinished both. I find that sometimes onPageFinished you won't get notify if you front end using react-router or something similar. And onReceivedTitle has flaw as @michael-levy mentioned.
private WebViewClient mWvClient = new WebViewClient() {
@Override
public void doUpdateVisitedHistory(WebView view, String url, boolean isReload) {
String title = view.getTitle();//getTitle
super.doUpdateVisitedHistory(view, url, isReload);
}
}
My observation is that, you get the webpage title using WebChromeClient
in lesser time than using WebViewClient
webview.setWebChromeClient(new WebChromeClient() {
@Override
public void onReceivedTitle(WebView view, String title) {
super.onReceivedTitle(view, title);
if (!TextUtils.isEmpty(title)) {
YourActivity.this.setTitle(title);
}
}
});
What if you do not want the whole title, and just a Domain Name, Like if you want to show only 'Google' from www.google.com, and you have all the query parameters in this title.
URL hostUrl= new URL(webView.getUrl());
String title = hostUrl.getHost();
title = title.startsWith("www.") ? title.substring(4) : title;
You'll have to use a custom WebViewClient to get this done. You will override the onPageFinished() method so when a new page finishes loading you can set the webview to the appropriate title.
Below is a sample implementation of the above:
WebView mWebView = (WebView) findViewById(R.id.mwebview);
mWebView.setWebViewClient(new WebViewClient() {
@Override
public void onPageFinished(WebView view, String url) {
ExperimentingActivity.this.setTitle(view.getTitle());
}
});
You're a going to do that where you're initializing your webview. Replace the "ExperimentingActivity" to whatever you activity's name is.
If you're already overriding the WebViewClient, just add this function or the code inside to your already existing function.
You can get more info on the classes and functions I'm using here at:
Android Developers: Activity - setTitle()
Android Developers: WebViewClient
Android Developers: WebView
get image and title from webview
Image
img.setImageBitmap(webview1.getFavicon());
Title
txt.setText(webview1.getTitle());