在WebView中的非可点击链接 [英] Non-clickable links in WebView

查看:151
本文介绍了在WebView中的非可点击链接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的应用程序,我从Web服务拉下一些HTML,并在网页视图显示它。在大多数情况下应用程序将显示在HTML链接就好了,因为在他们点击并打开Android浏览器。其他时候,然而,链接无法点击。事实证明,有时服务将提供HTML与不是一个href里面,只是纯文本链接。

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.

反正是有一个web视图来解析HTML,使这些链接点击?我知道,默认的Andr​​oid浏览器能做到这一点,但我不知道网页视图。

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.

推荐答案

web视图可能没有内置的一个页面内探测器自动链接平淡的网址,但你可以在网页视图中运行的JavaScript函数解析的网址当网页加载完成。

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.

基本上,类似如下(我没有检查这个code的语法还,但它应该给你的想法):

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

请注意,上面的JavaScript借用如何网址解析JavaScript的正则表达式与链路替代普通的网址吗?等详细信息可在JavaScript注入了Android WebViewClient引用中和的 http://lexandera.com/2009/01/injecting-javascript-into-a-webview/ (不是我)。

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).

这篇关于在WebView中的非可点击链接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆