在网上查询相关资料, 都是使用相同的方式, 但是使用不起作用, 最终在实验成功的方式如下(方法差不多):
mWebView = (WebView) view.findViewById(R.id.webview);
mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.addJavascriptInterface(new MyJavaScriptInterface(), "HTMLOUT");
mWebView.setWebViewClient(new WebViewClient() {
@Override
public void onPageFinished(WebView view, String url) {
mWebView.loadUrl("javascript:window.HTMLOUT.processHTML('<head>'" +
"+document.getElementsByTagName('html')[0].innerHTML+'</head>');");
}
});
mWebView.loadUrl("http url");
在调用上述内容的方法上声明:
@SuppressLint({"JavascriptInterface", "SetJavaScriptEnabled", "AddJavascriptInterface"})
编写本地接口
class MyJavaScriptInterface {
@JavascriptInterface
@SuppressWarnings("unused")
public void processHTML(String html) {
// process the html as needed by the app
Log.i("htmllll", "processHTML: ===" + html);
parseVideoData(html);
}
}
组合起来如下:
public class htmlParseActivity extends Activity {
@Override
@SuppressLint({"JavascriptInterface", "SetJavaScriptEnabled", "AddJavascriptInterface"})
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mWebView = (WebView) view.findViewById(R.id.webview);
mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.addJavascriptInterface(new MyJavaScriptInterface(), "HTMLOUT");
mWebView.setWebViewClient(new WebViewClient() {
@Override
public void onPageFinished(WebView view, String url) {
mWebView.loadUrl("javascript:window.HTMLOUT.processHTML('<head>'" +
"+document.getElementsByTagName('html') [0].innerHTML+'</head>');");
}
});
mWebView.loadUrl("http url");;
}
class MyJavaScriptInterface {
@JavascriptInterface
@SuppressWarnings("unused")
public void processHTML(String html) {
// process the html as needed by the app
Log.i("htmllll", "processHTML: ===" + html);
parseVideoData(html);
}
}
}