mSetting = mWebView.getSettings();
mSetting.setJavaScriptEnabled(true);
mWebView.addJavascriptInterface(new InJavaScriptLocalObj(), "java_obj");
mWebView.setWebViewClient(new WebViewClient() {
@Override
public void onPageFinished(WebView view, String url) {
Toast.makeText(NewsDetailActivity.this, "onPageFinished", Toast.LENGTH_SHORT).show();
view.loadUrl("javascript:window.java_obj.getSource(document.documentElement.outerHTML);void(0)");
super.onPageFinished(view, url);
}
});
mWebView.loadUrl(url);
//自己定义的类
public final class InJavaScriptLocalObj {
//一定也要加上这个注解,否则没有用
@JavascriptInterface
public void getSource(String html) {
//取出HTML中P标签的文本内容,利用正则表达式匹配.
Pattern pattern=Pattern.compile("<p.*?>(.*?)</p>");
Matcher matcher = pattern.matcher(html);
StringBuffer sb=new StringBuffer();
while (matcher.find())
{
sb.append(matcher.group(1));
}
mHtmlText = sb.toString();
Log.e(TAG, sb.toString());
Toast.makeText(NewsDetailActivity.this,sb.toString(), Toast.LENGTH_SHORT).show();
}
}
- 可能需要等一段时间才会执行到getSource方法然后获得HTML内容,我这里等待了2~3分钟左右.