Thursday, 8 May 2014

Selenium WebDriver – Open a link in a new Window


We can use Action class to open a link in a new window.

Method and Description:


  • contextClick(WebElement onElement) - Performs a context-click at middle of the given element.
  • perform()- A convenience method for performing the actions without calling build() first.
  • sendKeys(java.lang.CharSequence... keysToSend) - Sends keys to the active element.

 

Example:

Below example opens w3schools.com
And click on “Learn HTML” link to open in new window.

package com.example.tests;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.interactions.Actions;
import org.testng.annotations.AfterSuite;
import org.testng.annotations.BeforeSuite;
import org.testng.annotations.Test;
public class OpenLinkInNewWindowExample {
private WebDriver driver;
@BeforeSuite
public void setUp() throws Exception {
driver = new FirefoxDriver();
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
}
@AfterSuite
public void tearDown() throws Exception {
driver.quit();
}
@Test
public void testMethod(){
driver.get("http://www.w3schools.com/");
Actions action = new Actions(driver);
action.contextClick(driver.findElement(By.linkText("Learn HTML"))).perform();
action.sendKeys("w").perform();
}
}

No comments:

Post a Comment