在渲染之前从webview获取Html

时间:2013-02-01 09:38:26

标签: java android html parsing webview

我正在使用android webview 我的目标是在渲染之前解析html

要做到这一点,我在pagefinish事件中添加了以下javascript到webview ..

public void onPageFinished(WebView view, String url)
{
    view.loadUrl("javascript:varhtmlString=document.getElementsByTagName('html')[0].innerHTML;"
                 +"document.getElementsByTagName('html')[0].innerHTML=window.HTMLOUT.parseHTML(htmlString);");              
}

但问题是在解析html之前出现闪回(原始html)

然后我监视日志,发现javascript正在pageFinish(异步)之后执行 为了使它同步我使用了等待通知机制并确保javasript在页面完成之前运行

但仍然存在同样的问题原始html在解析之前出现

有没有办法在渲染之前更改html ????

1 个答案:

答案 0 :(得分:1)

你可以这样做:

String content = getContentForUrl(url);
String manipulateHTML  = manipulate(content); // your function to adjust the content.

webView.loadDataWithBaseURL(url, manipulateHTML, "text/html","UTF-8", null);

public String getContentForUrl(String url) {

    BufferedReader in = null;

    String content = "";

    try {
        HttpClient client = new DefaultHttpClient();
        HttpGet request = new HttpGet(url);
        HttpResponse response = client.execute(request);

        in = new BufferedReader(new InputStreamReader(response.getEntity()
                .getContent()));

        StringBuffer sb = new StringBuffer("");
        String line = "";
        String NL = System.getProperty("line.separator");

        while ((line = in.readLine()) != null) {
            sb.append(line + NL);
        }

        in.close();
        content = sb.toString();

        Log.d("MyApp", "url content for " + url + " " + content);

    } catch (Exception e) {

        Log.d("MyApp",
                "url content for " + url + " Exception :" + e.toString());

    } finally {
        if (in != null) {
            try {
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    return content;
}