Question

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?

Was it helpful?

Solution

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top