Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
190 views
in Technique[技术] by (71.8m points)

java - Verification of Element in Viewport in Selenium

How to verify whether an element is visible in viewport(visibility of browser) or not using Selenium?

I've tried with the below code, but Point object(Y value) returns huge value as page is scrollable. Here am getting element dimensions, location and Dimensions of Browser and comparing them.

Dimension weD = element.getSize(); //to get the element Dimensions
Point weP = element.getLocation(); // getting the location of the element in the page.

Dimension d = driver.manage().window().getSize(); // To get the browser dimensions
int x = d.getWidth(); //browser width
int y = d.getHeight(); //browser height
int x2 = weD.getWidth() + ewp.getX();
int y2 = weD.getHeight() + ewp.getY();
return x2 <= x && y2 <= y; 

If anyone has worked on it, Could you please share the solution?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

It's not possible directly via the API, so you'll have to use a script injection.

The best way to determine if an element is visible in the viewport is to get the element at the supposed location with document.elementFromPoint. It returns null if it's not within the viewport and your element or a descendant if it is.

public static Boolean isVisibleInViewport(WebElement element) {
  WebDriver driver = ((RemoteWebElement)element).getWrappedDriver();

  return (Boolean)((JavascriptExecutor)driver).executeScript(
      "var elem = arguments[0],                 " +
      "  box = elem.getBoundingClientRect(),    " +
      "  cx = box.left + box.width / 2,         " +
      "  cy = box.top + box.height / 2,         " +
      "  e = document.elementFromPoint(cx, cy); " +
      "for (; e; e = e.parentElement) {         " +
      "  if (e === elem)                        " +
      "    return true;                         " +
      "}                                        " +
      "return false;                            "
      , element);
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...