Clicking an element using javascript vs actions vs webdriver?

后端 未结 1 710
Happy的楠姐
Happy的楠姐 2021-02-13 18:13

We can click web-element using the following methods.

myWebElement.click();

or

JavascriptExecutor js = (JavascriptExecutor) dr         


        
1条回答
  •  旧巷少年郎
    2021-02-13 19:00

    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:

    
    
    
    
    
    

    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

    0 讨论(0)
提交回复
热议问题