irbash
irbash

Reputation: 43

execute Javascript in htmlUnit

I am trying to execute javascript using htmlUnit. After executing the javascript, I want to check if the page had some changes due to javascript execution. i.e I want to compare the html page before and after javascript execution...

Any ideas how I can do it...

Here's the sample code explaining what I actually intent to do...

public static void main(String[] args) {
    final WebClient webClient = new WebClient();

    HtmlPage page;
    try {
        page = webClient
                .getPage("http://www.somepage.com");
        System.out.println(page.asXml());
        System.out.println(page.getByXPath("//script"));

        BufferedInputStream buffer = null;
        // System.out.print("getWebSite " + urlValue + "\n");

        URL url = new URL(
                "http://www.somepage.com/someJS.js");
        HttpURLConnection urlc = (HttpURLConnection) url.openConnection();
        buffer = new BufferedInputStream(urlc.getInputStream());

        StringBuilder builder = new StringBuilder();
        int byteRead;
        while ((byteRead = buffer.read()) != -1)
            builder.append((char) byteRead);

        buffer.close();

        ScriptResult result = page.executeJavaScript(builder.toString());
        Object jsResult = result.getJavaScriptResult();

        HtmlPage afterExecution = (HtmlPage) result.getNewPage();

        System.out.println(afterExecution.asXml());

    } catch (FailingHttpStatusCodeException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (MalformedURLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

Upvotes: 2

Views: 12209

Answers (1)

Rodney Gitzel
Rodney Gitzel

Reputation: 2710

"Executing" the Javascript source won't do anything. I expect you get very little back from result.getNewPage(). Try changing the example to hit a real site, and explain what result you expect to see, then we can try executing your example.

That said, one thing that might help you is to think of HtmlUnit as a browser you control via Java. You don't "run" the Javascript in a page, HtmlUnit runs it. You pretend you are a human user clicking on things, but you do the "clicking" via Java code.

In your example, you would navigate the DOM in your page to find something that you use to trigger the Javascript -- perhaps clicking a button or an image. The result of calling click() will give you a new page resulting from whatever the Javascript did.

Upvotes: 1

Related Questions