Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clicking an element using javascript vs actions vs webdriver?

We can click web-element using the following methods.

myWebElement.click();

or

JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("arguments[0].click();", myWebElement);

or

Actions(driver).click(myWebElement).build().perform();

What is the difference in these methods?

like image 331
Ragunath Chilkuru Avatar asked Aug 17 '15 07:08

Ragunath Chilkuru


1 Answers

myWebElement.click();

Actions(driver).click(myWebElement).build().perform();

Both click method and actions class belong to webdriver.Action class is used for emulating complex user gestures(including actions such as Drag and Drop or clicking multiple elements With Control key etc).click method is used to click on the respective webElement(buttons,links etc).Selenium Webdriver uses browser's native support for mapping the DOM element to WebElement object using locators like id/xpath etc.

JavaScriptExecutor is an interface which provides mechanism to execute Javascript through selenium driver. It provides “executescript” & "executeAsyncScript" methods, to run external JavaScript in the context of the currently selected frame or window.In the case of executescript it will return an DOM element which is then converted to WebElement

The click simulated by WebDriver on a browser is similar to what actual user do as compared to one invoked using javascript

Example scenario:

<html>
<body>
<button type = "button" id ="test" style = "display:none"> clickme </button>
</body>
</html>

If you click on the "click me" button using click function in webdriver you will get an org.openqa.selenium.ElementNotVisibleException (Element not visible exception) which is correct as the element is present in the DOM but is not displayed to the user as the css style display:none is set

((JavascriptExecutor)driver).executeScript("$('#test').click();");//or
((JavascriptExecutor)driver).executeScript("document.getElementById('test').click();");

If you use the above javascript/jquery to click on the element then it will click on the button regardless of whether the button was visible or not which is wrong because the end user will not be able to see/click on the button but your script will pass.So the moral is try to use webdriver functions wherever possible instead of using javascript

Hope this helps you.Kindly get back if you have any queries

like image 118
Vicky Avatar answered Oct 27 '22 08:10

Vicky