Kuldip Bairagi
Kuldip Bairagi

Reputation: 109

Getting Html from webview before rendering

I am working with android webview my objective is to parse html before rendering

to do this i added following javascript to webview in pagefinish event..

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

but problem is a flash back (original html) appears before parse html

then i monitor logs and found that javascript is executing after pageFinish (asynchronously) for making it synchronous i used wait notify mechanism and ensure that javasript gets run before page finish

but still the same problem original html appears before parse

is there is a way to change html before rendering ????

Upvotes: 0

Views: 1264

Answers (1)

noam
noam

Reputation: 86

You can do it this way:

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

Upvotes: 1

Related Questions