Example usage for org.openqa.selenium WebDriver manage

List of usage examples for org.openqa.selenium WebDriver manage

Introduction

In this page you can find the example usage for org.openqa.selenium WebDriver manage.

Prototype

Options manage();

Source Link

Document

Gets the Option interface

Usage

From source file:org.xwiki.test.ui.WebDriverFactory.java

License:Open Source License

public WebDriver createWebDriver(String browserName) {
    WebDriver driver;
    if (browserName.startsWith("*firefox")) {
        // Native events are disabled by default for Firefox on Linux as it may cause tests which open many windows
        // in parallel to be unreliable. However, native events work quite well otherwise and are essential for some
        // of the new actions of the Advanced User Interaction. We need native events to be enable especially for
        // testing the WYSIWYG editor. See http://code.google.com/p/selenium/issues/detail?id=2331 .
        FirefoxProfile profile = new FirefoxProfile();
        profile.setEnableNativeEvents(true);
        // Make sure Firefox doesn't upgrade automatically on CI agents.
        profile.setPreference("app.update.auto", false);
        profile.setPreference("app.update.enabled", false);
        profile.setPreference("app.update.silent", false);
        driver = new FirefoxDriver(profile);

        // Hide the Add-on bar (from the bottom of the window, with "WebDriver" written on the right) because it can
        // prevent buttons or links from being clicked when they are beneath it and native events are used.
        // See https://groups.google.com/forum/#!msg/selenium-users/gBozOynEjs8/XDxxQNmUSCsJ
        // We need to load a page before sending the keys otherwise WebDriver throws ElementNotVisible exception.
        driver.get("data:text/plain;charset=utf-8,XWiki");
        driver.switchTo().activeElement().sendKeys(Keys.chord(Keys.CONTROL, "/"));
    } else if (browserName.startsWith("*iexplore")) {
        driver = new InternetExplorerDriver();
    } else if (browserName.startsWith("*chrome")) {
        driver = new ChromeDriver();
    } else if (browserName.startsWith("*phantomjs")) {
        DesiredCapabilities capabilities = DesiredCapabilities.phantomjs();
        capabilities.setCapability("handlesAlerts", true);
        try {/*from   www . j  ava  2 s  .  c  o  m*/
            driver = new PhantomJSDriver(ResolvingPhantomJSDriverService.createDefaultService(), capabilities);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    } else {
        throw new RuntimeException("Unsupported browser name [" + browserName + "]");
    }

    // Maximize the browser window by default so that the page has a standard layout. Individual tests can resize
    // the browser window if they want to test how the page layout adapts to limited space. This reduces the
    // probability of a test failure caused by an unexpected layout (nested scroll bars, floating menu over links
    // and buttons and so on).
    driver.manage().window().maximize();

    return driver;
}

From source file:org.zaproxy.zap.extension.domxss.TestDomXSS.java

License:Apache License

private WebDriver getNewFirefoxDriver() {
    ProxyParam proxyParams = Model.getSingleton().getOptionsParam().getProxyParam();

    /*//from  w  w  w  .  ja  va  2s .  c  o m
     * TODO look at supporting other browsers
     * Notes:
     *    HtmlUnit just logs a _load_ of errors
     *    Chrome doesnt seem to find anything, possibly due to its XSS protection
     *    Phantom JS doesnt find anything as 'alerts' arent yet supported
     */

    //WebDriver driver = ExtensionSelenium.getWebDriver(
    //      Browser.FIREFOX, proxyParams.getProxyIp(), proxyPort);

    // Proxy through ZAP
    String zapProxy = proxyParams.getProxyIp() + ":" + proxyPort;
    Proxy proxy = new Proxy();
    proxy.setHttpProxy(zapProxy).setSslProxy(zapProxy);
    DesiredCapabilities cap = new DesiredCapabilities();
    cap.setCapability(CapabilityType.PROXY, proxy);
    WebDriver driver = new FirefoxDriver(cap);

    driver.manage().timeouts().pageLoadTimeout(10, TimeUnit.SECONDS);
    driver.manage().timeouts().setScriptTimeout(10, TimeUnit.SECONDS);

    return driver;

}

From source file:PokemonGoMapValidator.Config.java

public void configInstance(String driverFile, String profileFile, String mapFile) {
    WebDriver webDriver = null;

    try {//from w  w w  .j a  va  2  s.  c  om
        System.setProperty("webdriver.chrome.driver", driverFile);

        String currentDirectory = Paths.get(".").toAbsolutePath().normalize().toString();

        ZipFile zipFile = new ZipFile(profileFile);
        zipFile.extractAll(currentDirectory + "/" + "profile" + "/");

        File f = new File(currentDirectory + "/prints/");
        if (!f.isDirectory()) {
            new File(currentDirectory + "/prints/").mkdir();
        }

        HashMap<String, Object> chromePrefs = new HashMap<>();
        chromePrefs.put("profile.default_content_settings.popups", 0);
        chromePrefs.put("download.default_directory", currentDirectory);

        ChromeOptions options = new ChromeOptions();

        //se na user-data-dir nao existir profile do chrome,  gerado um na hora
        options.addArguments("user-data-dir=" + currentDirectory + "/" + "profile");
        options.addArguments("--start-maximized");
        //adicionei esta linha, j que dns e portos andam sempre em mudanas
        options.addArguments("--dns-prefetch-disable");
        //options.addExtensions(new File(extensionFile));
        options.setExperimentalOption("prefs", chromePrefs);

        DesiredCapabilities capabilities = new DesiredCapabilities();
        capabilities.setCapability(CapabilityType.ACCEPT_SSL_CERTS, true);
        capabilities.setCapability(ChromeOptions.CAPABILITY, options);
        webDriver = new ChromeDriver(capabilities);

        //pokemongos grow in sextagon shape, so I will force a square resolution
        webDriver.manage().window().setPosition(new Point(XCOORD, YCOORD));
        if (MAPDIMENSION > 0) {
            webDriver.manage().window().setSize(new Dimension(MAPDIMENSION, MAPDIMENSION));
        } else {
            webDriver.manage().window().maximize();
        }

        //in the code below, I tried to create a square, but the width's and height's
        //seem to change, and I didn't figured out why and how
        //TODO in the future
        /*
        webDriver.get("http://www.google.com");
        Thread.sleep(1000);
        Dimension win_size = webDriver.manage().window().getSize();
                
        WebElement html = webDriver.findElement(By.tagName("html"));
        int inner_width = Integer.parseInt(html.getAttribute("clientWidth"));
        int outer_width = win_size.width - inner_width;
        int inner_height = Integer.parseInt(html.getAttribute("clientHeight"));
        int outer_height = win_size.height - inner_height;
                
        //pokemongos grow in sextagon shape, so I will force a square resolution
        webDriver.manage().window().setPosition(new Point(0, -1080));
        webDriver.manage().window().setSize(new Dimension(800 + outer_width, 600 + outer_height));
                
        if (VALIDATEBROWSER) {
        new Graphics().browserDimension(webDriver);
        }
                
        */

        RunComparison comparison = new RunComparison();
        comparison.comparison(currentDirectory, webDriver, mapFile);

    } catch (ZipException | IOException | InterruptedException ex) {
        System.err.println("Config error: " + ex.getMessage());
    } finally {
        try {
            if (webDriver != null) {
                Exit sair = new Exit();
                sair.exit(webDriver);
                System.out.println("ChromeDriver and Chrome unloaded");
            }
        } catch (InterruptedException ex) {
            System.err.println("Exit error: " + ex.getMessage());
        }
    }
}

From source file:PokemonGoMapValidator.Graphics.java

public void browserDimension(WebDriver driver) throws InterruptedException {

    System.out.println("Opening browser...");

    driver.get("http://www.google.com");
    Thread.sleep(1000);/* w  w  w. j av  a  2s  . co m*/
    //driver.manage().window().maximize();
    Dimension win_size = driver.manage().window().getSize();
    System.out.println("Browser border dimensions :");

    WebElement html = driver.findElement(By.tagName("html"));
    int inner_width = Integer.parseInt(html.getAttribute("clientWidth"));
    int outer_width = win_size.width - inner_width;
    System.out.println("Left + right border width: " + outer_width);
    int inner_height = Integer.parseInt(html.getAttribute("clientHeight"));
    int outer_height = win_size.height - inner_height;
    System.out.println("Top + bottom border height: " + outer_height);

    graphicsDevice();

    try {
        if (driver != null) {
            Exit sair = new Exit();
            sair.exit(driver);
            System.out.println("ChromeDriver and Chrome unloaded");
            System.exit(0);
        }
    } catch (InterruptedException ex) {
        System.err.println("Exit error: " + ex.getMessage());
    }
}

From source file:Practice.Tool.java

License:Open Source License

/**
  * Wait for the element to be present in the DOM, and displayed on the page. 
  * And returns the first WebElement using the given method.
  * /*w  w w .  ja v a 2s  . c  om*/
  * @param WebDriver   The driver object to be used 
  * @param By   selector to find the element
  * @param int   The time in seconds to wait until returning a failure
  *
  * @return WebElement   the first WebElement using the given method, or null (if the timeout is reached)
  */

public static WebElement waitForElement(WebDriver driver, final By by, int timeOutInSeconds) {
    WebElement element;
    try {
        //To use WebDriverWait(), we would have to nullify implicitlyWait(). 
        //Because implicitlyWait time also set "driver.findElement()" wait time.  
        //info from: https://groups.google.com/forum/?fromgroups=#!topic/selenium-users/6VO_7IXylgY

        driver.manage().timeouts().implicitlyWait(0, TimeUnit.SECONDS); //nullify implicitlyWait() 

        WebDriverWait wait = new WebDriverWait(driver, timeOutInSeconds);
        element = wait.until(ExpectedConditions.visibilityOfElementLocated(by));

        driver.manage().timeouts().implicitlyWait(DEFAULT_WAIT_4_PAGE, TimeUnit.SECONDS); //reset implicitlyWait
        return element; //return the element   
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}

From source file:Practice.Tool.java

License:Open Source License

public static WebElement waitForNavigateBack(WebDriver driver, final By by, int timeOutInSeconds) {
    WebElement element;/*from   w w  w .  j  a v a2  s .  c o m*/
    try {
        driver.manage().timeouts().implicitlyWait(0, TimeUnit.SECONDS); //nullify implicitlyWait() 
        new WebDriverWait(driver, timeOutInSeconds) {
        }.until(new ExpectedCondition<Boolean>() {

            @Override
            public Boolean apply(WebDriver driverObject) {
                driverObject.navigate().back(); // Waiting to go back to the previous Page
                return isElementPresentAndDisplay(driverObject, by);
            }
        });
        element = driver.findElement(by);
        driver.manage().timeouts().implicitlyWait(DEFAULT_WAIT_4_PAGE, TimeUnit.SECONDS); //reset implicitlyWait
        return element; //return the element
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}

From source file:Practice.Tool.java

License:Open Source License

/** 
 * Waits for the Condition of JavaScript.  
 *
 *
 * @param WebDriver      The driver object to be used to wait and find the element
 * @param String   The javaScript condition we are waiting. e.g. "return (xmlhttp.readyState >= 2 && xmlhttp.status == 200)" 
 * @param int   The time in seconds to wait until returning a failure
 * @return /*from  w w  w . j a v a 2  s  . c  om*/
 * 
 * @return boolean true or false(condition fail, or if the timeout is reached)
 **/
public static void waitForJavaScriptCondition(WebDriver driver, final String javaScript, int timeOutInSeconds) {
    //boolean jscondition = false; 
    try {
        driver.manage().timeouts().implicitlyWait(0, TimeUnit.SECONDS); //nullify implicitlyWait() 
        new WebDriverWait(driver, timeOutInSeconds) {
        }.until(new ExpectedCondition<WebElement>() {

            @Override
            public WebElement apply(WebDriver driverObject) {
                ((JavascriptExecutor) driverObject).executeScript(javaScript);
                return null;
            }
        });
        ((JavascriptExecutor) driver).executeScript(javaScript);
        driver.manage().timeouts().implicitlyWait(DEFAULT_WAIT_4_PAGE, TimeUnit.SECONDS); //reset implicitlyWait
        //return jscondition; 
    } catch (Exception e) {
        e.printStackTrace();
    }
    //return false; 
}

From source file:qsp.popups.ActiTimewinhand.java

public static void main(String[] args) throws Throwable {
    WebDriver driver = new FirefoxDriver();
    driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);

    driver.get("http://localhost/login.do");
    driver.findElement(By.id("licenseLink")).click();

    driver.findElement(By.xpath("//a[.='actiTIME Inc.']")).click();
    Set<String> allwh = driver.getWindowHandles();
    System.out.println(allwh.size());
    for (String aw : allwh) {
        driver.switchTo().window(aw);/*from  w  w w .  ja v  a  2 s .c  om*/
        System.out.println(driver.switchTo().window(aw));
        driver.close();
    }

}

From source file:renascere.Renascere.java

License:Open Source License

/**
 * @Description Method that gets current browser cookies and veries it number based on the inputs
 * @param driver -- Browser object to be used to gather the information
 * @param numberCookies  -- Expected number of cookies expected. 
 */// w w w.  jav a 2s  .  c o  m
public static void checkCookies(WebDriver driver, int numberCookies) {
    //Getting cookies information
    Set<Cookie> seleniumCookies = driver.manage().getCookies();
    int currentCookies = driver.manage().getCookies().size();
    if (currentCookies == numberCookies) {
        logMessage(result.PASS, "Number of cookies is correct (" + currentCookies + ").");
        for (Cookie seleniumCookie : seleniumCookies) {
            logMessage(result.INFO,
                    "c.Name: " + seleniumCookie.getName() + " ||| c.Value: " + seleniumCookie.getValue()
                            + " ||| c.Domain: " + seleniumCookie.getDomain() + " ||| c.Path: "
                            + seleniumCookie.getPath() + " ||| c.Expiry: " + seleniumCookie.getExpiry()
                            + " ||| c.Class: " + seleniumCookie.getClass());
        }
    } else {
        logMessage(result.WARNING, "Number of cokkies is not the expected: " + currentCookies);
    }
}

From source file:ru.stqa.selenium.logging.LoggingWebDriver.java

License:Apache License

private void dumpBrowserLogs(WebDriver driver) {
    try {/* www  . j a  va2  s  .  co  m*/
        for (LogEntry logEntry : driver.manage().logs().get("browser").getAll()) {
            BROWSER_LOG.debug("" + logEntry);
        }
    } catch (Throwable e) {
    }
}