Saturday, March 15, 2014

Open in new Tab or new Window in Selenium Webdriver

New Tab:
Use the below code to complete the action in a new tab.
WebDriver driver = new FirefoxDriver();
driver.get("http://aksahu.blogspot.in/");
You can  do by either of the below ways
driver.findElement(By.linkText("Tips & Tricks")).sendKeys(Keys.CONTROL + "t");
Or
WebElement aLink = driver.findElement(By.linkText("Tips & Tricks"));
Actions actions = new Actions(driver);
actions.moveToElement(aLink);
actions.contextClick(aLink)
       .sendKeys(Keys.ARROW_DOWN)
       .sendKeys(Keys.ENTER).build().perform();

New Window:
Use the below code to complete the action in a new window.
WebDriver driver = new FirefoxDriver();
driver.get("http://aksahu.blogspot.in/");
Open a web page in a new window:
String script = "var d=document,a=d.createElement('a');a.target='_blank';a.href='%s';a.innerHTML='.';d.body.appendChild(a);return a";
Object element = ((JavascriptExecutor) driver).executeScript(String.format(script, "http://aksahu.blogspot.in/"));
if (element instanceof WebElement) {
    WebElement anchor = (WebElement) element;
    anchor.click();
    ((JavascriptExecutor) driver).executeScript("var a=arguments[0];a.parentNode.removeChild(a);", anchor);
} else {
     throw new JavaScriptException(element, "Unable to open Window", 1);
}
Open a link in a new window:
WebElement elemLink = driver.findElement(By.linkText("Web Driver"));
Actions actions = new Actions(driver);
actions.moveToElement(elemLink);
actions.contextClick(elemLink)
       .sendKeys(Keys.ARROW_DOWN)
       .sendKeys(Keys.ARROW_DOWN)
       .sendKeys(Keys.ENTER).build().perform();

No comments:

Post a Comment