Brito Brito - 2 months ago 8
Java Question

Selenium hangs after executing jscript command

I'm trying to click in a dynamic menu executing the following method:

public void clicaItemSubMenu(String item) throws InterruptedException{
String link = driver.findElement(By.xpath("//*[contains(text(), '" + item + "')]")).getAttribute("Id");
driver.get("javascript:document.getElementById('" + link + "').click()");
}


The code works just fine and the menu is being opened and after that,
Selenium
hangs for FireFox or Internet Explorer. The issue does not happen if I debug the code. I've tried to deal with some wait stuff but, no success. Can anyone help?

Answer

Actually WebDriver::get() is used to load a new web page in the current browser window. This is done using an HTTP GET operation, and the method will block until the load is complete while you want to perform click on element using JavaScript.

You should try using JavascriptExecutor::executeScript() which executes JavaScript in the context of the currently selected frame or window as below :-

public void clicaItemSubMenu(String item) throws InterruptedException{
  WebElement link = driver.findElement(By.xpath("//*[contains(text(), '" + item + "')]"));
  ((JavascriptExecutor)driver).executeScript("arguments[0].click()", link);
 }

Note :- You can directly click on WebElement using WebElement::click() method as link.click() without using JavascriptExecutor.