Question

After referring many articles on SO and google, couldn't find a solution for my question.

The question is, am fetching the hostname in onPageFinished method of WebViewClient class. Problem arises when getHost() returns me the hostname multiple times. But I would like to have a SINGLE hostname.

For example: When I open bmw.com website, getHost() returns me www.bmw.com twice, and m.bmw.com thrice for the same webpage.

Tried with onPageStarted, but the result is similar.

Even tried WebChromeClient to get the title, but can't rely as sometimes it doesn't return a title.

Is there a way to get a SINGLE hostname after the page loads?

Here is my code

public void onPageFinished(WebView view, String url4){

        String urlHost = null;
        try {
            urlHost = new URL(url4).getHost().toString();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }

        addressBarTextView.setText(urlHost);
    }
Was it helpful?

Solution

Fist a couple of observations:

  1. The reason you're seeing multiple onPageFinished calls are most likely redirects.
  2. Unfortunately there isn't a reliable way for you to determine when a redirect chain has ended (especially in the presence of JavaScript-initiated redirects that occur after a timeout).
  3. I don't know of a reliable way to do what you want based on the URL alone. Consider how would you decide what the host bit is of "my-app.appspot.com" or "2.my-app.appspot.com"?
  4. browsers also have this problem - if you go to a page that does a couple of redirects you'll see the address bar change.

That being said there are a couple of things you could do:

  • If the host changing too frequently is only a UI problem (that is - it just looks bad) maybe throttle the changes (don't allow it to change more often than once per second, for example (don't forget about the last update with the final/current URL))?
  • Have a set of best-effort transformation rules (like "m.*" -> "www.*"), if you do this I'd recommend having some option for the user to see the 'real' URL too.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top