當頁面加載完成時,您可以使用WebView的Javascript接口返回整個HTML源代碼。爲此,您需要將您自己的WebViewClient分配給WebView。
要做到這一點,使用類似於你的Activity類以下的東西 - 確保您的活動實現觀察員:
public void onCreate(Bundle savedInstanceState) {
// ...
webView.setWebViewClient(new MyWebViewClient());
HtmlJSInterface htmlJSInterface = new HtmlJSInterface();
webView.addJavascriptInterface(htmlJSInterface, "HTMLOUT");
htmlJSInterface.addObserver(this);
// ...
}
// Called when our JavaScript Interface Observables are updated.
@Override
public void update(Observable observable, Object observation) {
// Got full page source.
if (observable instanceof HtmlJSInterface) {
html = (String) observation;
onHtmlChanged();
}
}
private void onHtmlChanged() {
// Do stuff here...
}
private class MyWebViewClient extends WebViewClient {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
@Override
public void onPageFinished(WebView view, String url) {
// When each page is finished we're going to inject our custom
// JavaScript which allows us to
// communicate to the JS Interfaces. Responsible for sending full
// HTML over to the
// HtmlJSInterface...
isStarted = false;
isLoaded = true;
timeoutTimer.cancel();
view.loadUrl("javascript:(function() { "
+ "window.HTMLOUT.setHtml('<html>'+"
+ "document.getElementsByTagName('html')[0].innerHTML+'</html>');})();");
}
}
}
然後,你將要創建的HtmlJSInterface類,因此:
public class HtmlJSInterface extends Observable {
private String html;
/**
* @return The most recent HTML received by the interface
*/
public String getHtml() {
return this.html;
}
/**
* Sets most recent HTML and notifies observers.
*
* @param html
* The full HTML of a page
*/
public void setHtml(String html) {
this.html = html;
setChanged();
notifyObservers(html);
}
}
您是否嘗試過某些東西?這樣做時你遇到任何問題嗎?你需要建築建議嗎?因爲這個網站不是代碼分配器。 –
可否請你提供完整的源代碼,我不能管理上面的代碼工作.. 謝謝 –