Selenium webdriver switchin tab - selenium

I am unable to open google in new tab please review this code :
public static void main (String [] args) throws InterruptedException, AWTException
{
System.setProperty("webdriver.chrome.driver","C://Users//vbisht//Downloads//chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.navigate().to("https://www.google.co.in/");
Robot r = new Robot();
r.keyPress(KeyEvent.VK_CONTROL);
r.keyPress(KeyEvent.VK_T);
//Thread.sleep(10000);
//driver.navigate().refresh();*/
ArrayList<String> tabs = new ArrayList<String> (driver.getWindowHandles());
driver.switchTo().window(tabs.get(1)); //switches to new tab
driver.navigate().to("https://www.google.co.in/");

String parentWindowHandler=driver.getWindowHandle();// Store your parent window
String subWindowHandler = null;
Set<String> handles = driver.getWindowHandles(); // get all window handles
Iterator<String> iterator = handles.iterator();
while (iterator.hasNext()){
subWindowHandler = iterator.next();
}
driver.switchTo().window(subWindowHandler); // switch to popup window
Hope it will help you.

Try the below code,
The code below will open the link in new Tab.
String selectLinkOpeninNewTab = Keys.chord(Keys.CONTROL,Keys.RETURN);
driver.findElement(By.linkText("urlLink")).sendKeys(selectLinkOpeninNewTab);
The code below will open empty new Tab.
String selectLinkOpeninNewTab = Keys.chord(Keys.CONTROL,"t");
driver.findElement(By.linkText("urlLink")).sendKeys(selectLinkOpeninNewTab);

Instead of using Robot Class, You can simply open it with Javascript Executor
public static void main (String [] args) throws InterruptedException, AWTException { System.setProperty("webdriver.chrome.driver","C://Users//vbisht//Downloads//chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.navigate().to("https://www.google.co.in/");
((JavascriptExecutor) driver).executeScript("window.open()");
ArrayList<String> tabs = new ArrayList<String> (driver.getWindowHandles());
driver.switchTo().window(tabs.get(1)); //switches to new tab
driver.navigate().to("https://www.google.co.in/");
}

To open two different urls in two different TABs, once you initiate opening a new tab/window you have to induce WebDriverWait and then collect the window handles and finally iterate through the window handles and then switchTo().window(newly_opened) as per the following example:
Sample Code:
System.setProperty("webdriver.chrome.driver", "C:\\Utility\\BrowserDrivers\\chromedriver.exe.exe");
WebDriver driver = new InternetExplorerDriver();
driver.get("http://www.google.com");
String first_tab = driver.getWindowHandle();
System.out.println("Working on Google");
((JavascriptExecutor) driver).executeScript("window.open('http://facebook.com/');");
WebDriverWait wait = new WebDriverWait(driver,5);
wait.until(ExpectedConditions.numberOfWindowsToBe(2));
Set<String> s1 = driver.getWindowHandles();
Iterator<String> i1 = s1.iterator();
while(i1.hasNext())
{
String next_tab = i1.next();
if (!first_tab.equalsIgnoreCase(next_tab))
{
driver.switchTo().window(next_tab);
System.out.println("Working on Facebook");
}
}
Console Output:
Working on Google
Working on Facebook

Related

Selenium can't locate/read elements when browser extension (crumbs.crx) GPC is ON and it automatically opens new child window (which is should not)

Selenium can't locate/read elements when browser extension (crumbs.crx) GPC is ON and it automatically opens new child window (which is should not), I can switch to child window and can send tab keys but unable to locate/find the elements in which I should be able to input text/data. Any inputs are appreciated. Thanks in advance.
Switch window code:
public void switchWindow() {
String mainwindow = driver.getWindowHandle();
Set<String> s1 = driver.getWindowHandles();
Iterator<String> i1 = s1.iterator();
while (i1.hasNext()) {
String ChildWindow = i1.next();
if (!mainwindow.equalsIgnoreCase(ChildWindow)) {
driver.switchTo().window(ChildWindow);
String pageTitle=driver.getTitle();
log.info("Page title " + pageTitle);
driver.close();
System.out.println("Child window closed");
}
}
driver.switchTo().window(mainwindow);
String pageTitle=driver.getTitle();
log.info("Page title " + pageTitle);
}
Loading browser extension code:
public void loadBrowserExtension(String fileName) {
boolean remote = Boolean.getBoolean("remote");
ChromeOptions options = new ChromeOptions();
options.addExtensions(new File(Common_Page.class
.getResource("/data/testdata/" + fileName).getPath()));
if (remote) {
driver = driverUtil.getSeleniumGridDriver(options);
} else {
WebDriverManager.chromedriver().setup();
driver = new ChromeDriver(options);
}
driver.manage().timeouts().implicitlyWait(3L, TimeUnit.SECONDS);
driver.manage().window().setSize(new Dimension(1366, 768 + 45));
log.info("****** Screen Size: " + driver.manage().window().getSize() + "******");
DriverFactory.destroyDriver();
WaitUtils.waitSleep(10000);
WaitUtils.updateDriver(driver);
driverUtil.setDriver(driver);

Drag and drop in Selenium

In https://www.globalsqa.com/demo-site/draganddrop/ I need to drag and drop picture with the text "High Tatras" into Trash section.
#Test
void task1() {
System.setProperty("webdriver.chrome.driver", "C:\\Users\\DELL\\Desktop\\New folder\\chromedriver.exe");
WebDriver webDriver = new ChromeDriver();
try {
webDriver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS);
webDriver.get("https://www.globalsqa.com/demo-site/draganddrop/");
WebElement from = webDriver.findElement(By.xpath("//*[#id=\"gallery\"]/li[1]"));
WebElement to = webDriver.findElement(By.xpath("//*[#id=\"trash\"]"));
Actions actions = new Actions(webDriver);
actions.dragAndDrop(from, to).build().perform();
} finally {
webDriver.close();
}
}
Both the from and to elements are inside the iframe.
So, to access these elements you need to switch into that iframe first.
Your code will look as following:
#Test
void task1() {
System.setProperty("webdriver.chrome.driver", "C:\\Users\\DELL\\Desktop\\New folder\\chromedriver.exe");
WebDriver webDriver = new ChromeDriver();
try {
webDriver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS);
webDriver.get("https://www.globalsqa.com/demo-site/draganddrop/");
driver.switchTo().frame(driver.findElement(By.xpath("//div[#rel-title='Photo Manager']//iframe")));
WebElement from = webDriver.findElement(By.xpath("//*[#id='gallery']/li[1]"));
WebElement to = webDriver.findElement(By.xpath("//*[#id='trash']"));
Actions actions = new Actions(webDriver);
actions.dragAndDrop(from, to).build().perform();
} finally {
webDriver.close();
}
}

How to handle the pop-up as webpage and alert both simultaneously?

Please help me to fill this form and then going on to the website along with handling the alert.
Here is my code which is not working:
public class FirstCry {
public static void main(String[] args) throws InterruptedException {
System.setProperty("webdriver.chrome.driver", "D:\\Selenium\\CP-SAT\\Chromedriver\\chromedriver.exe");
WebDriver a = new ChromeDriver();
a.get("http://www.firstcry.com/");
Thread.sleep(5000L);
a.manage().window().maximize();
String k = a.getPageSource();
System.out.println(k);
WebDriverWait Wait = new WebDriverWait(a, 30);
Wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath(".//*[#id='amt']/div[2]/div[1]/div[1]/div[3]/div")));
WebElement b = a.findElement(By.xpath(".//*[#id='amt']/div[2]/div[1]/div[1]/div[3]/div"));
b.click();
}
}
In your website popup present inside an iframe with id iframe_Login, you need to switch that iframe before finding the close button of the popup as below :-
//Create this prefs to handle notification popup
Map<String, Object> prefs = new HashMap<String, Object>();
prefs.put("profile.default_content_setting_values.notifications", 2);
//Initialize chrome option to add prefs
ChromeOptions options = new ChromeOptions();
options.setExperimentalOption("prefs", prefs);
//Now initialize chrome driver with chrome option to handle notification alert
WebDriver a = new ChromeDriver(options)
a.get("http://www.firstcry.com/");
a.manage().window().maximize();
WebDriverWait wait = new WebDriverWait(a, 30)
//Now find iframe and switch to it
wait.until(ExpectedConditions.frameToBeAvailableAndSwitchToIt("iframe_Login"));
//Now find the popup close button
WebElement b = wait.until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector("div[class = '_pop_close _pop_reg_bg']")));
b.click();
//Now switch back from frame to default content for further steps
a.switchTo().defaultContent();
//Now do your further stuff
Hope it helps..:)

How to switch to newly opened tab and close it?

I have used the below two methods to switch to the tab and close it.But unfortunately, none of them are useful.Please provide alternate methods.
sol1:
public static void switchTab()
{
try{
webDriver.findElement(By.cssSelector("body")).sendKeys(Keys.CONTROL, Keys.PAGE_DOWN);
webDriver.close();
webDriver.findElement(By.cssSelector("body")).sendKeys(Keys.CONTROL, Keys.PAGE_DOWN);
}
catch(Exception e){
e.printStackTrace();}
}
}
Here, driver is closing the whole browser instead of closing the tab.
sol2:
public void switchTab(){
try{
ArrayList<String> tabs2 = new ArrayList<String> (webDriver.getWindowHandles());
webDriver.switchTo().window(tabs2.get(1));
webDriver.close();
webDriver.switchTo().window(tabs2.get(0));
}
catch(Exception e){
e.printStackTrace();}
}
This is throwing index out of bounds exception as there is no other window opened.
Try below code
String homeWindow = driver.getWindowHandle();
Set<String> allWindows = driver.getWindowHandles();
//Use Iterator to iterate over windows
Iterator<String> windowIterator = allWindows.iterator();
//Verify next window is available
while(windowIterator.hasNext()){
//Store the Recruiter window id
String childWindow = windowIterator.next();
//Here we will compare if parent window is not equal to child window
if (homeWindow.equals(childWindow)){
driver.switchTo().window(childWindow);
//switch here to your desired window/tab and perform your action
driver.close();
}
Hope it will help you :)
If Understand correctly then, this will might help
put this in function block.
WebDriver driver = new FirefoxDriver();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.manage().window().maximize();
driver.get("http://google.com");
String gettitle = driver.getTitle();
String windowHandel = driver.getWindowHandle();
System.out.println(windowHandel + " " + gettitle);
driver.findElement(By.cssSelector("body")).sendKeys(Keys.CONTROL+"t");
ArrayList tabs = new ArrayList(driver.getWindowHandles());
System.out.println(tabs.size());
driver.switchTo().window((String) tabs.get(0));
gettitle ="";
driver.get("http://bing.com");
gettitle = driver.getTitle();
System.out.println(tabs.get(0).toString() + " " + gettitle);
driver.switchTo().window(windowHandel);
Thread.sleep(3000);
Actions actionObj = new Actions(driver);
actionObj.keyDown(Keys.CONTROL)
.sendKeys(Keys.chord("w"))
.keyUp(Keys.CONTROL)
.perform();
driver.switchTo().defaultContent();

Unable to control slider captcha jquery using Selenium Webdrive?

I want to record slider captcha given on our client site.
We have get this concept from other site named as http://www.fmylife.com/signup
This have slider captcha for registration
I have try to use selenium webdriver action builder
public class TestFmylife {
WebDriver driver;
Selenium selenium;
#BeforeMethod
public void startSelenium() {
driver = new FirefoxDriver();
selenium = new WebDriverBackedSelenium(driver, "http://www.fmylife.com/");
driver.manage().window().maximize();
}
#AfterMethod
public void stopSelenium() {
driver.close();
}
#Test
public void testFmylife() {
selenium.open("/");
selenium.click("link=Sign up");
selenium.waitForPageToLoad("30000");
selenium.type("name=login", "testfmylife");
selenium.type("name=pass", "123#fmylife");
selenium.type("name=passc", "123#fmylife");
selenium.type("name=mail", "testfmylife#gmail.com");
Point MyPoint= driver.findElement(By.xpath("//*[#id='bgSlider']")).getLocation();
WebElement someElement = driver.findElement(By.xpath("//*[#id='bgSlider']"));
System.out.println(MyPoint.x+"--------"+MyPoint.y);
Actions builder = new Actions(driver);
Action dragAndDrop = builder.clickAndHold(someElement).moveByOffset(MyPoint.x,(MyPoint.y + 100)).release().build();
dragAndDrop.perform();
selenium.click("css=div.form > div.ok > input[type=\"submit\"]");
}
}
But I can't move slider using this code
Help me to sort this out
I used the dragAndDropBy method of the Actions class (java.lang.Object
org.openqa.selenium.interactions.Actions) and moved the slider by 200 points horizontally . Please give the following code a try:
WebDriver driver = new FirefoxDriver();
driver.get("http://www.fmylife.com/signup");
WebElement slider = driver.findElement(By.xpath(".//*[#id='Slider']"));
Actions builder = new Actions (driver);
builder.dragAndDropBy(slider, 200, 0).build().perform();
Actions builder = new Actions(driver);
Action dragAndDrop = builder.clickAndHold(someElement)
.moveToElement(otherElement)
.release(otherElement)
.build();
dragAndDrop.perform();
more can be found at - http://code.google.com/p/selenium/wiki/AdvancedUserInteractions
You can use locator as follows -
String xto=Integer.toString(LocatorTo.getLocation().x);
String yto=Integer.toString(LocatorTo.getLocation().y);
Working code-
WebDriver driver = new InternetExplorerDriver();
driver.get("http://jqueryui.com/demos/slider/");
//Identify WebElement
WebElement slider = driver.findElement(By.xpath("//div[#id='slider']/a"));
//Using Action Class
Actions move = new Actions(driver);
Action action = move.dragAndDropBy(slider, 30, 0).build();
action.perform();
driver.quit();
Source - https://gist.github.com/2497551
If your slider is like mine
with a "slider handle" (an <a/> tag as the box with the value "5ft 5") within a "slider track" (a <div> tag as the long black bar) then the following code will in C# will work to move the slider handle a percentage along the slider track.
public void SetSliderPercentage(string sliderHandleXpath, string sliderTrackXpath, int percentage)
{
var sliderHandle = driver.FindElement(By.XPath(sliderHandleXpath));
var sliderTrack = driver.FindElement(By.XPath(sliderTrackXpath));
var width = int.Parse(sliderTrack.GetCssValue("width").Replace("px", ""));
var dx = (int)(percentage / 100.0 * width);
new Actions(driver)
.DragAndDropToOffset(sliderHandle, dx, 0)
.Build()
.Perform();
}