根据标题,我正在尝试获取当前webview内容的HTML。我就是这样做的:
WebView webView = (WebView)findViewById(R.id.webView);
webView.getSettings().setJavaScriptEnabled(true);
WVClient wvClient = new WVClient();
wvClient.setFirst(true);
webView.setWebViewClient(wvClient);
webView.addJavascriptInterface(new MyJavaScriptInterface(this), "HtmlViewer");
webView.setWebChromeClient(new WebChromeClient() {
public void onProgressChanged(WebView view, int progress){
progressBar.setProgress(progress);
}
});
webView.loadUrl("http://www.somthing.com");
MyJavaScriptInterface类:
public class MyJavaScriptInterface {
private Context ctx;
MyJavaScriptInterface(Context ctx) {
this.ctx = ctx;
}
public void showHTML(String html) {
Log.i("log","showHTML: "+html);
}
}
WVClient类:
public class WVClient extends WebViewClient {
private boolean first;
public WVClient() {
super();
setFirst(false);
}
public void onPageFinished(WebView view, String url) {
// TODO Auto-generated method stub
super.onPageFinished(view, url);
if(first){
builder.append("javascript:__doPostBack('promotions_landing$A1','');");
builder.append("javascript:window.HtmlViewer.showHTML('<html>'+document.getElementsByTagName('html')[0].innerHTML+'</html>');");
view.loadUrl(builder.toString());
setFirst(false);
}
}
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
public boolean isFirst() {
return first;
}
public void setFirst(boolean first) {
this.first = first;
}
}
一切似乎都是对的,但它不起作用。不调用MyJavascriptInterface中的showHTML()。我错过了什么?
答案 0 :(得分:0)
我找到了答案。 Mistake位于MyJavaScriptInterface类,JavascriptInterface类实现了Annotation,因此注释@JavascriptInterface必须在MyJavaScriptInterface类中编写,如下所示,并且没有类构造函数。
MyJavaScriptInterface类:
public class MyJavaScriptInterface{
@JavascriptInterface
public void showHTML(String html) {
Log.i("log","showHTML: "+html);
}
}
webView的addJavascriptInterface相应更改如下:
webView.addJavascriptInterface(new MyJavaScriptInterface(), "HtmlViewer");