本文介绍了获取HTML在Android网页视图不工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

按标题,我试图获取当前视图内容的HTML。这就是我如何做到这一点:

As per title, I am trying to get HTML of current webview content. This is how I do it:

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类:

MyJavaScriptInterface class:

public class MyJavaScriptInterface {

    private Context ctx;

    MyJavaScriptInterface(Context ctx) {
        this.ctx = ctx;
    }

    public void showHTML(String html) {
        Log.i("log","showHTML: "+html);
    }

}

WVClient类:

WVClient Class:

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;
}

}

似乎一切权利,但它不工作。 showHTML()在MyJavascriptInterface不叫。什么我错过了?

Everything seems right, but it's not working. showHTML() in MyJavascriptInterface is not called. What have I missed?

推荐答案

我已经找到了答案。错误是在MyJavaScriptInterface类,JavascriptInterface类实现了这样的注释@JavascriptInterface已被写入如下MyJavaScriptInterface类注释,有没有类构造函数。

I have found the answer. Mistake is at MyJavaScriptInterface class, JavascriptInterface class implements Annotation thus annotation @JavascriptInterface has to be written in MyJavaScriptInterface class as below and there's no class constructor.

MyJavaScriptInterface类:

MyJavaScriptInterface class:

public class MyJavaScriptInterface{

   @JavascriptInterface
   public void showHTML(String html) {
       Log.i("log","showHTML: "+html);
   }
}

和的WebView addJavascriptInterface变化如下相应:

And webView's addJavascriptInterface change accordingly as below:

webView.addJavascriptInterface(new MyJavaScriptInterface(), "HtmlViewer");

这篇关于获取HTML在Android网页视图不工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-14 04:28