Why doesn't HtmlUnitDriver execute JavaScript?

匆匆过客 提交于 2019-11-29 13:12:29

You can enable JavaScript by doing either

  • new HtmlUnitDriver(true);
  • driver.setJavascriptEnabled(true);

What you need to do is to wait until the JavaScript is executed after get(url).

You can use Thread.sleep() method for adding some delay.

HtmlUnitDriver driver = new HtmlUnitDriver(BrowserVersion.FIREFOX_3_6);
driver.setJavascriptEnabled(true);
driver.get(url);

Thread.sleep(100);

runTest();

Update

As @Corey indicated in the comments, it could be nicer to use Explicit and Implicit Waits instead of Thread.sleep(). As I don't use them these days, I cannot confirm, though. It would be great if someone test them and update this answer.

You need to initialize the HtmlUnitDriver with enable javascript true

new HtmlUnitDriver(true);

If you wish to set the BrowserVersion as well as enable Javascript with HtmlUnitDriver, your initialization needs to look like the following (as there is no way to do both via the constructor):

HtmlUnitDriver driver = new HtmlUnitDriver(BrowserVersion.FIREFOX_3_6);
driver.setJavascriptEnabled(true);

This will allow you to use the browser definition of your choice and use Javascript.

user1307037

You may need to do this:

WebDriver driver = new HtmlUnitDriver(BrowserVersion.INTERNET_EXPLORER_8);
((HtmlUnitDriver) driver).setJavascriptEnabled(true);

Well, There is an easy way to enable browser capability and javascript, you can do the following:

Webdriver driver = new HtmlUnitDriver(BrowserVersion.Chrome,true);

True specifies that javascript should be enabled. @Glenn Nelson,

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