2014-02-12 31 views
0

我需要從HTML字符串中加載頁面,而不是從服務器加載頁面。JavaScript onload事件不會在HtmlUnit中觸發

我使用this answer發現方法:

String html = "<html><head><script>" + 
       "alert('hey 1'); " + 
       "function OnLoadEvent() { alert('hey 2'); }" + 
       "</script></head>" + 
       "<body onload='OnLoadEvent()'></body></html>" 

URL url = new URL("http://www.example.com"); 
StringWebResponse response = new StringWebResponse(html, url); 
WebClient client = new WebClient() 
client.getOptions().setJavaScriptEnabled(true); 
HtmlPage page = HTMLParser.parseHtml(response, client.getCurrentWindow()); 

我還設置AlertHandler如下:

client.setAlertHandler(new AlertHandler() { 
    @Override 
    public void handleAlert(Page arg0, String arg1) { 
     System.out.println("ALERT: " + arg1); 
    } 
}); 

的示例HTML上述警報 「哎1」 僅 - 我期望它提醒「嗨1」和「嘿2」 - 這意味着身體onload事件不發射。

有什麼額外的我需要做的,以使onload事件觸發?

+0

你的問題解決了? – Kick

回答

3

我錯過了撥打電話HtmlPage.initialize()

+1

Thnsk的答案,解決方案也幫助我 – Kick