3

I have been working on a script for hours and I can't seem to figure out a way to make headless and automated automated.

    WebDriver driver = new HtmlUnitDriver(
            BrowserVersion.INTERNET_EXPLORER_11, true);

    driver.get("site");

    WebDriverWait wait = new WebDriverWait(driver, 60);
    wait.until(ExpectedConditions.visibilityOfElementLocated(By
            .className("vote-apple")));

    WebElement apple = driver.findElement(By.className("vote-apple"));
    apple.click();

While this works if I switch my driver to FirefoxDriver, it seems to break when I run this code with a HTMLUnit Driver.

com.gargoylesoftware.htmlunit.ScriptException: TypeError: Cannot call method

If you have any clues as to why this is happening, it would be greatly appreciated.

Thanks!

2 Answers 2

6

You can ignore javascript errors by changing WebClient options. You just need to extend HtmlUnitDriver class in such way.

public class CustomHtmlUnitDriver extends HtmlUnitDriver {

...

 @Override
    protected WebClient modifyWebClient(WebClient client) {
        WebClient modifiedClient = super.modifyWebClient(client);
        modifiedClient.getOptions().setThrowExceptionOnScriptError(false); // see here
        return modifiedClient;
    }
}

and an example of CustomHtmlUnitDriver usage:

CustomHtmlUnitDriver driver = new CustomHtmlUnitDriver();
driver.setJavascriptEnabled(true);
driver.get("https://google.com");
1
  • 1
    @Bart, please accept this answer. It helped me, and it was upvoted several times before.
    – kriegaex
    Feb 20 at 4:12
1

What I got from the Selenium site is that JavaScript is disabled by default in HtmlUnit and it seems you have enabled it in your script and that's why you may be getting this issue. Try, once with default settings of the HtmlUnit i.e. with JavaScript as disabled.

With WebDriver, we had to make a choice; do we enable HtmlUnit’s JavaScript capabilities and run the risk of teams running into problems that only manifest themselves there, or do we leave JavaScript disabled, knowing that there are more and more sites that rely on JavaScript? We took the conservative approach, and by default have disabled support when we use HtmlUnit.

In addition to it, you will find from this post over SO that using HtmlUnit will/may cause lots of issue with JavaScript and it is a pain area. It also tells that one facing the issue as mentioned by you, should try the same script with different browser versions, so you should try the same with IE 10 (it that works for you).

1
  • Hey Dhiman, Thanks for the response. Unfortunately, Javascript is required for the click function to work. I'm currently testing out other solutions. Will report back if I find anything.
    – Bart
    Oct 30, 2015 at 0:17

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.