Verification of Element in Viewport in Selenium

后端 未结 2 1121
不思量自难忘°
不思量自难忘° 2020-12-03 16:10

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) retu

2条回答
  •  借酒劲吻你
    2020-12-03 16:30

    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);
    }
    

提交回复
热议问题