Example usage for org.openqa.selenium WebElement getSize

List of usage examples for org.openqa.selenium WebElement getSize

Introduction

In this page you can find the example usage for org.openqa.selenium WebElement getSize.

Prototype

Dimension getSize();

Source Link

Document

What is the width and height of the rendered element?

Usage

From source file:myfightinglayoutbugs.DetectElementsWithInvisibleFocus.java

License:Apache License

private FocusedElement toFocusedElement(@Nonnull WebElement activeElement, WebPage webPage) {
    // I don't trust WebDriver, that's why I determine the offset, width and height with jQuery too ...
    @SuppressWarnings("unchecked")
    Map<String, Object> temp = (Map<String, Object>) JsonHelper
            .parse((String) webPage
                    .executeJavaScript(//  www .j a v a2s.c  om
                            "var $element = jQuery(arguments[0]);\n" + "var offset = $element.offset();\n"
                                    + "var $temp = $element.clone(false).wrap('<div></div>').parent();\n"
                                    + "try {\n" + "    return JSON.stringify({\n" + "        x: offset.left,\n"
                                    + "        y: offset.top,\n" + "        w: $element.width(),\n"
                                    + "        h: $element.height(),\n" + "        html: $temp.html()\n"
                                    + "    });\n" + "} finally {\n" + "    $temp.remove();\n" + "}",
                            activeElement));
    int x = ((Number) temp.get("x")).intValue();
    int y = ((Number) temp.get("y")).intValue();
    int w = ((Number) temp.get("w")).intValue();
    int h = ((Number) temp.get("h")).intValue();
    String html = (String) temp.get("html");
    if (activeElement.isDisplayed()) {
        //Point location = 
        //activeElement.getLocation().getX();
        //Dimension size = activeElement.getSize().height;
        int x1 = Math.min(activeElement.getLocation().getX(), x);
        int y1 = Math.min(activeElement.getLocation().getY(), y);
        int x2 = Math.max(activeElement.getLocation().getX() + activeElement.getSize().getWidth(), x + w) - 1;
        int y2 = Math.max(activeElement.getLocation().getY() + activeElement.getSize().getHeight(), y + h) - 1;
        return new FocusedElement(activeElement, new RectangularRegion(x1, y1, x2, y2), html);
    } else {
        return new FocusedElement(activeElement, NOT_DISPLAYED, html);
    }
}

From source file:net.codestory.simplelenium.filters.LazyShould.java

License:Apache License

private static boolean hasDimension(WebElement element, int width, int height) {
    Dimension dimension = element.getSize();
    return dimension.getWidth() == width && dimension.getHeight() == height;
}

From source file:net.codestory.simplelenium.filters.LazyShould.java

License:Apache License

private static String dimension(WebElement element) {
    return element.getSize().toString();
}

From source file:org.callimachusproject.webdriver.helpers.WebBrowserDriver.java

License:Apache License

public int getPositionBottom(By locator) {
    WebElement element = driver.findElement(locator);
    return element.getLocation().getY() + element.getSize().getHeight();
}

From source file:org.finra.jtaf.ewd.utils.ScreenshotUtils.java

License:Apache License

/***
 * You can use this method to take your control pictures. Note that the file should be a png.
 * //w  w  w .  j  a  v  a2  s  .  c  o m
 * @param element
 * @param toSaveAs
 * @throws IOException 
 * @throws WidgetException 
 * @throws WidgetTimeoutException 
 * @throws Exception
 */
public static void takeScreenshotOfElement(IElement element, File toSaveAs)
        throws IOException, WidgetException {

    for (int i = 0; i < 10; i++) { //Loop up to 10x to ensure a clean screenshot was taken
        log.info("Taking screen shot of locator " + element.getLocator() + " ... attempt #" + (i + 1));

        //Scroll to element
        element.scrollTo();

        //Take picture of the page
        WebDriver wd = SessionManager.getInstance().getCurrentSession().getWrappedDriver();
        File screenshot;
        boolean isRemote = false;
        if (!(wd instanceof RemoteWebDriver)) {
            screenshot = ((TakesScreenshot) wd).getScreenshotAs(OutputType.FILE);
        } else {
            Augmenter augmenter = new Augmenter();
            screenshot = ((TakesScreenshot) augmenter.augment(wd)).getScreenshotAs(OutputType.FILE);
            isRemote = true;
        }
        BufferedImage fullImage = ImageIO.read(screenshot);
        WebElement ele = element.getWebElement();

        //Parse out the picture of the element
        Point point = ele.getLocation();
        int eleWidth = ele.getSize().getWidth();
        int eleHeight = ele.getSize().getHeight();
        int x;
        int y;
        if (isRemote) {
            x = ((Locatable) ele).getCoordinates().inViewPort().getX();
            y = ((Locatable) ele).getCoordinates().inViewPort().getY();
        } else {
            x = point.getX();
            y = point.getY();
        }
        log.debug("Screenshot coordinates x: " + x + ", y: " + y);
        BufferedImage eleScreenshot = fullImage.getSubimage(x, y, eleWidth, eleHeight);
        ImageIO.write(eleScreenshot, "png", screenshot);

        //Ensure clean snapshot (sometimes WebDriver takes bad pictures and they turn out all black)
        if (!isBlack(ImageIO.read(screenshot))) {
            FileUtils.copyFile(screenshot, toSaveAs);
            break;
        }
    }
}

From source file:org.finra.jtaf.ewd.widget.element.InteractiveElement.java

License:Apache License

@Override
public void mouseMoveOut() throws WidgetException {
    try {//w  w  w .  j av a2  s  . c  om
        // TODO: Need to figure out whether 10 is sufficient
        int offsetAmount = 10;

        WebElement elem = getWebElement();
        Dimension dim = elem.getSize();
        int width = dim.getWidth();
        Actions builder = new Actions(getGUIDriver().getWrappedDriver());
        synchronized (InteractiveElement.class) {
            getGUIDriver().focus();
            builder.moveToElement(getWebElement(), width + offsetAmount, 0).build().perform();
        }
    } catch (Exception e) {
        throw new WidgetException("Error while performing mouse move out", getLocator(), e);
    }
}

From source file:org.jitsi.meet.test.VideoLayoutTest.java

License:Apache License

/**
 * Checks if the video container fits the inner window width and height.
 *
 * @param webDriver <tt>WebDriver</tt> instance of the participant for whom
 *                  we'll try to check the video size
 */// www . j a  va  2 s.  c  o m
private void doLargeVideoSizeCheck(WebDriver webDriver) {
    Long innerWidth = (Long) ((JavascriptExecutor) webDriver).executeScript("return window.innerWidth;");

    Long innerHeight = (Long) ((JavascriptExecutor) webDriver).executeScript("return window.innerHeight;");

    WebElement largeVideo = webDriver.findElement(By.xpath("//div[@id='largeVideoContainer']"));

    assertEquals(largeVideo.getSize().getWidth(), innerWidth.intValue());
    assertEquals(largeVideo.getSize().getHeight(), innerHeight.intValue());

    // now let's check whether the video wrapper take all the height
    // this should not be the case only for desktop sharing with thumbs
    // visible
    WebElement largeVideoWrapper = webDriver.findElement(By.xpath("//div[@id='largeVideoWrapper']"));

    assertEquals(largeVideoWrapper.getSize().getHeight(), innerHeight.intValue());
}

From source file:org.jspringbot.keyword.selenium.SeleniumHelper.java

License:Open Source License

public void mouseOut(String locator) {
    LOG.createAppender().appendBold("Mouse Out:").appendCss(locator).log();

    WebElement el = finder.find(locator);

    if (el == null) {
        throw new IllegalStateException(String.format("ERROR: Element %s not found", locator));
    }/*  w  w  w. j av  a  2 s  .c  o m*/

    Dimension size = el.getSize();
    int offsetX = (size.getWidth() / 2) + 1;
    int offsetY = (size.getHeight() / 2) + 1;

    new Actions(driver).moveToElement(el).moveByOffset(offsetX, offsetY).perform();
}

From source file:org.julianharty.accessibility.automation.KeyboardHelpers.java

License:Apache License

/**
 * Uses the tab key to navigate around a web page.
 *
 * Helps determine which elements are reachable with the tab key and
 * whether the first active element can be reached again (indicating we
 * can 'loop' around the tabable elements on the page.
 *
 * Any iFrames are visited recursively./*w w  w .j  ava2s.c  om*/
 * 
 * A sample call follows:
 * <code><br/>
public void testTabbingThroughGoogleSearchResults() throws InterruptedException { <br/>
   FirefoxDriver driver = new FirefoxDriver(); <br/>
   driver.get("http://www.google.com/search?q=cheese"); <br/>
   int maxTabsToEnter = 300; <br/>
   int tabs = KeyboardHelpers.tabThroughWebPage(driver, maxTabsToEnter);<br/>
   assertTrue("Expected at least 50 tabs, only needed " + tabs, tabs > 50);<br/>
 } </code>
 *
 * @param driver a WebDriver connection with the target page loaded.
 * @param maxTabsToEnter the maximum tabs we should need to visit all the
 * tabable elements. Consider providing a 2x or 3x the expected number,
 * particularly for complex, unknown content.  
 * @return the number of tabs issued if the method reached an element that
 * matched the first active element, else -1 if it failed to complete
 * within the specified number of tabs. 
 * @throws InterruptedException if the call to sleep fails. 
 */
public static int tabThroughWebPage(WebDriver driver, int maxTabsToEnter) throws InterruptedException {

    WebElement firstElement = driver.switchTo().activeElement();
    WebElement currentElement = firstElement;
    currentSize = firstElement.getSize();

    int tabsIssued = 0;
    int iFrame = 0;
    String currentTagName = "(not set)";
    try {
        while (tabsIssued < (maxTabsToEnter)) {
            Point currentLocation = currentElement.getLocation();
            logDetailsOfWebElement(currentElement, currentLocation, tabsIssued);
            currentTagName = currentElement.getTagName();

            /*
             * for iframes switch to the iframe and call ourself recursively. We
             * think it always starts from _top of the iframe. That call will
             * tab until it 'falls out' of the active elements in the iframe.
             * Body will then be returned, then we need to switch back to the
             * parent.
             * 
             * Note: use periods to separate nested frames.
             */

            if (currentTagName.equals("iframe")) {
                driver.switchTo().frame(iFrame++);
                // A simple calculation to limit tabs in a 'broken' iFrame for now.
                tabThroughWebPage(driver, maxTabsToEnter - tabsIssued);
                // Will the following skip over the 'body' of the iFrame?
                driver.switchTo().defaultContent();
                currentElement = driver.switchTo().activeElement();
            }

            String currentTitle = getTitleOfCurrentElement(driver, currentElement);

            // Here is one of the termination conditions, if we find one of our titles.
            if (currentTitle.contains(TAB_KEYWORD + 0)) {
                logTerminationCondition(
                        String.format("Title %s of element matches the value set", currentTitle),
                        currentElement, tabsIssued);
                return tabsIssued;
            }

            setWebElementAttributesAsAppropriate(driver, currentElement, tabsIssued, currentTagName);

            currentElement.sendKeys(Keys.TAB); // "\t" also works
            tabsIssued++;
            // TODO 2011Aug16 Don't sleep with IE driver, it's too slow
            // Thread.sleep(500L);

            String previousTagName = currentTagName;
            Point previousLocation = currentLocation;
            Dimension previousSize = currentSize;
            currentElement = driver.switchTo().activeElement();
            currentLocation = currentElement.getLocation();
            currentSize = currentElement.getSize();
            currentTagName = currentElement.getTagName();

            /* Loop termination is still imprecise. Typically the first element
             * is the body element, however in some GWT applications it's a div
             * element for reasons I don't yet fathom. 
             * TODO(jharty): improve the precision and reliability of the 
             * matching as we learn more about how to interact with elements
             * on the page. 
             */

            if (GeneralHelpers.locationMatches(currentLocation, previousLocation)
                    && GeneralHelpers.dimensionsAreEqual(currentSize, previousSize)
                    && currentTagName.equals(previousTagName) && !currentTagName.equals("body")) {
                logTerminationCondition(String.format(
                        "Bad news: Element %s seems to match %s after tabbing. Are NativeEvents working?",
                        currentTagName, previousTagName), currentElement, tabsIssued);
                // Tell the user to check native events are working
                return -1;
            }

            if (currentElement.equals(firstElement) && tabsIssued >= 3) {
                logTerminationCondition("Current element matches first element", currentElement, tabsIssued);
                return tabsIssued;
            }
        }
    } catch (WebDriverException wde) {
        String innerHTML = (String) ((JavascriptExecutor) driver)
                .executeScript("return arguments[0].innerHTML;", currentElement);
        LOG.warning(String.format("Current Tag %s, InnerHTML for problem element is %s", currentTagName,
                innerHTML));
        throw wde;
    }
    return -1;
}

From source file:org.mule.modules.selenium.SeleniumModule.java

License:Open Source License

/**
 * What is the width and height of the rendered element?
 * <p/>//from   w w  w .j av a 2s . c o  m
 * {@sample.xml ../../../doc/mule-module-selenium.xml.sample selenium:get-size}
 *
 * @param element Element located at the payload of the message
 * @return The size of the element on the page.
 */
public Dimension getSize(@Payload WebElement element) {
    return element.getSize();
}