Javascript Scroll Element into View with Selenium used in a wrong way

Javascript Scroll Element into View with Selenium used in a wrong way

Everybody is pleased with the tests until some functionality is changed in the Front End, and tests are going to fail because the elements are not displayed. You are going to search for solutions for making the web element to be in the clickable state.

You have a considerable probability to find :

WebElement element = driver.findElement(By.id("id_of_element"));
driver.executeScript("arguments[0].scrollIntoView(true);", element);

By using this code snippet, we are using the default settings :

If true, the top of the element will be aligned to the top of the visible area of the scrollable ancestor. Corresponds to scrollIntoViewOptions: {block: "start", inline: "nearest"}. This is the default value.

accordingly, this link.

After playing in the chrome console, I discovered that the correct way of using the method is

WebElement element = driver.findElement(By.id("id_of_element"));
String script = "arguments[0].scrollIntoView({behavior: \"auto\", block: \"center\", inline: \"center\"});";
driver.executeScript(script, element);

Okay, too much theory, now let's make some things to happen by applying what we learned.

Steps to play:

  1. Open this link.
  2. Open the Chrome console(F12 or the dev tools)
  3. Go to console
  4. And execute the scripts:
var element = document.getElementById("Notes");
element.scrollIntoView();


var element = document.getElementById("Notes");
element.scrollIntoView(false);


var element = document.getElementById("Notes");
element.scrollIntoView({block: "center"});


var element = document.getElementById("Notes");

element.scrollIntoView({behavior: "smooth", block: "center", inline: "center"});

By running these scripts, I discovered that I am using in a wrong way the javascript code, and if you run as well, you will find the magic word center.

要查看或添加评论,请登录

社区洞察

其他会员也浏览了