0 votes
1 view
in Devops and Agile by (19.8k points)

In Selenium WebDriver, there are two major methods to put an element into a visible area:

  1. Scrolling into view:

((JavascriptExecutor) driver).executeScript("arguments[0].scrollIntoView(true);", element);

      2. Using moveToElement browser action:

Actions actions = new Actions(driver);

actions.moveToElement(element);

actions.perform();

Are these methods equivalent and which one should be preferred?

1 Answer

0 votes
by (63.4k points)

scrollIntoView

The DOM method scrollIntoViewonly scrolls the item in the view. If scrollIntoViewit cannot scroll through an item in a view, it simply fails. I added an invisible element to the beginning body and called it scrollIntoView. Nothing scrolled, but there was no error. Note that you have more control over how an item scrolls with help scrollIntoViewthan with help moveToElement. Selenium is only interested in presenting the element in sight so that the mouse can be placed on it. It does not give you any statements about how this will be done. scrollIntoViewhowever, it allows you, for example, to indicate whether you want the top or bottom of an element to be aligned with its scrollable ancestor. (For details, see here ).

 

moveToElement

The Selenium method moveToElement performs two functions: it scrolls an element in the view and moves the mouse over the element. I also tested it with elements that cannot be scrolled or moved because they do not have coordinates on the screen and have no error here.

 

Pick one

By default I use moveToElement, with the following exceptions:

 

1. If you do not want to influence at all where Selenium placed the mouse, but you want to scroll something insight (a bit strange ... but possible), then you should use scrollIntoView.

 

2. If you need to scroll an item with the kind of control that scrollIntoViewgives you (for example, the alignment parameter mentioned above), you should use it instead moveToElement.

 

3. There are cases when attempts to mimic user behavior using Selenium commands are impossible or very expensive to do by sending a series of Selenium commands. (Each team is a circuit in the network. When the testing server is somewhere over the Internet, it is added up.) In such cases, I use Selenium executeScript. In this case, it may be useful to use the scrollIntoView script, and then complete the script, create an Action scroll for execution, and complete the whole operation with the help of another executeScript

Welcome to Intellipaat Community. Get your technical queries answered by top developers !


Categories

...