2

In my app, I am pulling down some HTML from a web service and displaying it in a WebView. Most of the time the app will display links in the HTML just fine, as in they are clickable and open up the Android Browser. Other times, however, the links are not clickable. It turns out sometimes the service will provide HTML with links that are not inside an href, and are just plain text.

Is there anyway for a WebView to parse the HTML and make these links "clickable"? I know the default Android Browser can do it, but I'm not sure about WebViews.

SeanPONeil
  • 3,901
  • 4
  • 29
  • 42

1 Answers1

1

The Webview may not have built-in detectors to auto-link plain URLs within a page, but you could run a JavaScript function within the WebView to parse the URLs when the page finishes loading.

Basically, something like the following (I haven't checked this code for syntax yet, but it should give you the idea):

final WebView webview = (WebView)findViewById(R.id.browser);
/* JavaScript must be enabled if you want it to work, obviously */
webview.getSettings().setJavaScriptEnabled(true);

/* WebViewClient must be set BEFORE calling loadUrl! */
webview.setWebViewClient(new WebViewClient() {
    @Override
    public void onPageFinished(WebView view, String url)
    {
        webview.loadUrl("javascript:(function() { " +
                "var exp = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig; " +
                "document.getElementsByTagName('body')[0].innerHTML =  document.getElementsByTagName('body')[0].innerHTML.replace(exp,'<a href='$1'>$1</a>');" +
                "})()");
    }
});

webview.loadUrl("http://code.google.com/android");

Note that the above JavaScript borrows the URL-parsing JavaScript regex from " How to replace plain URLs with links?," and more info can be found on JavaScript injection within the Android WebViewClient reference and at http://lexandera.com/2009/01/injecting-javascript-into-a-webview/ (not me).

Community
  • 1
  • 1
Mike Fahy
  • 5,487
  • 4
  • 24
  • 28
  • 1
    I had to remove some of the escaping slashes to make Eclipse happy, and it looks like the webview is loading the function but it is not replacing anything. – SeanPONeil Nov 29 '11 at 16:39
  • Any chance you could post your final code? Most likely a simple JavaScript error. – Mike Fahy Nov 30 '11 at 02:05
  • I ended up going with this route http://stackoverflow.com/questions/8317364/string-replaceall-method-not-working the regular expression is slightly different – SeanPONeil Nov 30 '11 at 03:40