Javascript onload event not firing in HtmlUnit

别来无恙 提交于 2020-01-17 07:23:27

问题


I need to load a page from an HTML string, not from a server.

I use the method found in 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());

I have also set an AlertHandler as follows:

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

The example HTML above alerts "hey 1" only -- I would expect it to alert "hey 1" and "hey 2" -- this implies the body onload event is not firing.

Is there something extra I need to do to make the onload event fire?


回答1:


I was missing a call to HtmlPage.initialize().



来源:https://stackoverflow.com/questions/21733842/javascript-onload-event-not-firing-in-htmlunit

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!