Search code examples
javahttp-posthtmlunit

Navigating through a website by pressing on JS buttons using HTMLUnit


I'm attempting to press a Javascript Button on a webpage using HTMLUnit 2.36 which navigates to another page, and so on...:

ScriptResult result = page.executeJavaScript("__doPostBack('LinkBtn_thebutton','')");
Page page = result.getNewPage();

I've attempted to use the code above which causes the following error, supposedly because getNewPage() is no longer supported:

The method GetNewPage() is undefined for type ScriptResult

I've also attempted to add a cast with getJavaScriptResult() as shown below with no luck:

HtmlPage page1 = (HtmlPage) result.getJavaScriptResult();

Causing the following error:

Exception in thread "main" java.lang.ClassCastException: class net.sourceforge.htmlunit.corejs.javascript.Undefined cannot be cast to class com.gargoylesoftware.htmlunit.html.HtmlPage

Solution

  • You are not supposed to cast the result.getJavaScriptResult();, treat it like a void. If your page is going to be redirected, make sure that redirecting is enabled: webClient.getOptions().setRedirectEnabled(true);