2013-02-01 154 views
0

我與Android的WebView工作之前 我的目標是使從網頁流量獲取HTML渲染

做到這一點之前,解析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

你可以這樣來做:

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

什麼崗位要求? – gondo