selenium web driver - switch to parent window - java

I use selenium Web Driver. I have opened a parent window. After I click on the link the new window opens. I choose some value from the list and this window automatically closes. Now I need to operate in my parent window. How can I do this? I tried the following code:
String HandleBefore = driver.getWindowHandle();
driver.findElement(By.xpath("...")).click();
for (String Handle : driver.getWindowHandles()) {
driver.switchTo().window(Handle);}
driver.findElement(By.linkText("...")).click();
driver.switchTo().window(HandleBefore);
This does not work though.

Try this before you click the link that opens the new window:
parent_h = browser.current_window
# click on the link that opens a new window
handles = browser.window_handles # before the pop-up window closes
handles.remove(parent_h)
browser.switch_to_window(handles.pop())
# do stuff in the popup
# popup window closes
browser.switch_to_window(parent_h)
# and you're back

public boolean switchBackParentWindowTitle(String windowTitle){
boolean executedActionStatus = false;
try {
Thread.sleep(1000);
WebDriver popup = null;
Set<String> handles = null;
handles =driver.getWindowHandles();
Iterator<String> it = handles.iterator();
while (it.hasNext()){
String switchWin = it.next();
popup = driver.switchTo().window(switchWin);
System.out.println(popup.getTitle());
if(popup.getTitle().equalsIgnoreCase(windowTitle)){
log.info("Current switched window title is "+popup.getTitle());
log.info("Time taken to switch window is "+sw.elapsedTime());
executedActionStatus = true;
break;
}
else
log.info("WindowTitle does not found to switch over");
}
}
catch (Exception er) {
er.printStackTrace();
log.error("Ex: "+er);
}
return executedActionStatus;
}

This will not answer your question, however it might answer a similar one.
With SeleniumBase all you need to do is write:
self.switch_to_default_window()
And you're back to the parent window.

Related

How to check pop-up present in a page or not?

How to check "popup present" in a page or not?
Suppose in my 1st run pop up present in a page, but in my second run it doesn't appear on page? I am not expecting handling popups?
you can try this bellow code
//define your main window
String mainWindowHandler = driver.getWindowHandle();
//handle your popup
Set<String> popup = driver.getWindowHandles();
for (String winHandle : popup) {
if(!winHandle.equals(mainWindowHandler)) {
//switch to popup
driver.switchTo().window(winHandle);
System.out.println(driver.getTitle());
//close popup, or your action
driver.close();
//back to main window
driver.switchTo().window(mainWindowHandler);
}
}

Switch to pop up window using Selenium

I am trying to switch to a popup window but I am having trouble doing so. The link that I click on is to redirect me to an email popup window.
My code is:
public String determineIfCorrectUrlOnPopUp() {
clickOnEmailThisSeller();
for (String currentWindow: driver.getWindowHandles()) {
driver.switchTo().window(currentWindow);
}
System.out.println(driver.getCurrentUrl());
return driver.getCurrentUrl();
}
but it prints out the parent window URL instead of the popup window. I am not sure what I am doing wrong?
public String determineIfCorrectUrlOnPopUp() {
clickOnEmailThisSeller();
// Below Line in your code will switch to the current window by using for each loop
for (String currentWindow: driver.getWindowHandles())
driver.switchTo().window(currentWindow);
{
//Now you are in Popup window and you can get the pop-up window URL here
System.out.println(driver.getCurrentUrl());
driver.close();
}
System.out.println(driver.getCurrentUrl()); // This will return Parent window URL
return driver.getCurrentUrl();
}
Have you tried
driver.switchTo().window(handle).getCurrentUrl();
I haven't done a lot of this but I did write a little function that closes popup windows and I used
driver.switchTo().window(handle).close();
to close the popup.

Switch from child to parent window in Selenium Webdriver

I'm creating test scripts in Selenium WebSriver using Eclipse, and have hit a snag in a scenario whereby I have a parent window, I click on a link on that window and a child window opens. I then want to close the child window and carry out functions again on the parent window.
My code is as below:
public static void daysInStockSelectContract(InternetExplorerDriver driver) {
driver.findElement(By.xpath(".//*[#id='page-content']/table/tbody/tr[1]/td[1]/a")).click();
for(String winHandle : driver.getWindowHandles()) {
driver.switchTo().window(winHandle);
driver.close();
}
}
When I run the above code, the child window remains open whilst the parent window closes, which is the opposite effect of what I wanted. Also an error as follows is shown in the console:
"Exception in thread "main" org.openqa.selenium.remote.SessionNotFoundException: session 1ff55fb6-71c9-4466-9993-32d7d9cae760 does not exist"
I'm using IE WebDriver for my Selenium scripts.
UPDATE - 17/11/14
Subh, here is the code I used from the link you kindly send over which unfortunately doesn't appear to work.
public static void daysInStockSelectContract(InternetExplorerDriver driver) {
//get the parent handle before clicking on the link
String winHandleBefore = driver.getWindowHandle();
driver.findElement(By.xpath(".//*[#id='page-content']/table/tbody/tr[1]/td[1]/a")).click();
// the set will contain only the child window now. Switch to child window and close it.
for(String winHandle : driver.getWindowHandles()) {
driver.switchTo().window(winHandle);
}
driver.close();
driver.switchTo().window(winHandleBefore);
}
Probably, the switching to child window didn't happen properly.
Hence, 'driver.close()' is closing the parent window, instead of child window. Also, since the parent window has been closed, it implies the session has been lost which gives the error 'SessionNotFoundException'.
This link will help you out in properly switching between windows
On another note, just an advice. Rather than passing "driver" as a parameter, why don't you make it a static variable. It will be easily accessible to all the methods inside the class and it's subclasses too, and you don't have to bother about passing it each time to a method.. :)
Below is the code that you've requested in your comment (Unrelated to the question above)
public class Testing_anew {
public static WebDriver driver;
public static void main(String args[]) throws InterruptedException{
driver = new FirefoxDriver();
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
}
public static void testmethod(){
driver.findElement(By.xpath("//some xpath")).click();
}
Updated Code 19/11/14
public static void daysInStockSelectContract(InternetExplorerDriver driver) {
//get the parent handle before clicking on the link
String winHandleBefore = driver.getWindowHandle();
System.out.println("Current handle is: "+winHandleBefore);
driver.findElement(By.xpath(".//*[#id='page-content']/table/tbody/tr[1]/td[1]/a")).click();
// Iterating through the set of window handles till the child window's handle, that is infact
// not equal to the current window handle, is found
for(String winHandle : driver.getWindowHandles()) {
if(!winHandle.equals(winHandleBefore)){
System.out.println("Child handle is: "+ winHandle);
//Sleeping for 4 seconds for detecting Child window
try{
Thread.sleep(4000);
}catch(InterruptedException e){
System.out.println("Caught exception related to sleep:"+e.getMessage());
}
driver.switchTo().window(winHandle);
break;
}
}
System.out.println("AFTER SWITCHING, Handle is: "+driver.getWindowHandle());
driver.close();
//Sleeping for 4 seconds for detecting Parent window
try{
Thread.sleep(4000);
}catch(InterruptedException e){
System.out.println("Caught exception related to sleep:"+e.getMessage());
}
driver.switchTo().window(winHandleBefore); // Switching back to parent window
System.out.println("NOW THE CURRENT Handle is: "+driver.getWindowHandle());
//Now perform some user action here with respect to parent window to assert that the window has switched properly
}
When you loop through the windowHandles, the first handle is the parent handle. So when you say driver.close(), the parent window is getting closed. This can be avoided by using the following code:
public static void daysInStockSelectContract(InternetExplorerDriver driver) {
//get the parent handle before clicking on the link
String parentHandle = driver.getWindowHandle();
driver.findElement(By.xpath(".//*[#id='page-content']/table/tbody/tr[1]/td[1]/a")).click();
//get all the window handles and assign it to a set
//It will include child window and parentwindow
Set<String> windowHandles = driver.getWindowHandles();
System.out.println("No of Window Handles: " + windowHandles.size());
//remove the parent handle from the set
windowHandles.remove(parentHandle);
// the set will contain only the child window now. Switch to child window and close it.
for(String winHandle : driver.getWindowHandles()) {
strong text driver.switchTo().window(winHandle);
driver.close();
}
}
If you get the size as 1 (no of windowHandles as one) or is getting same error message, then probably the window is an alert box. To handle the alert box you can use the following code just after clicking on the link.
Alert alert = driver.switchTo().alert();
alert.accept();
Try this code for debugging
public static void daysInStockSelectContract(InternetExplorerDriver driver) {
// get the parent handle before clicking on the link
String parentHandle = driver.getWindowHandle();
System.out.println("ParentHandle : " + parentHandle);
driver.findElement(
By.xpath(".//*[#id='page-content']/table/tbody/tr[1]/td[1]/a"))
.click();
// get all the window handles and assign it to a set
// It will include child window and parentwindow
Set<String> windowHandles = driver.getWindowHandles();
System.out.println("No of Window Handles: " + windowHandles.size());
// remove the parent handle from the set
windowHandles.remove(parentHandle);
// the set will contain only the child window now. Switch to child
// window and close it.
for (String winHandle : driver.getWindowHandles()) {
driver.switchTo().window(winHandle);
System.out.println("Child Handle : " + winHandle);
driver.close();
}
// get the window handles again, print the size
windowHandles = driver.getWindowHandles();
System.out.println("No of Window Handles: " + windowHandles.size());
for (String winHandldes : windowHandles) {
System.out.println("Active Window : " + winHandldes);
}
driver.switchTo().window(parentHandle);
}
I managed to resolve this issue by using the steps outlined by Subh above. Especially, ensure that 'Enable Protected Mode' is disabled on the 'Security' tab of 'Internet Options'

How to handle the new window in Selenium WebDriver using Java?

This is my code:
driver.findElement(By.id("ImageButton5")).click();
//Thread.sleep(3000);
String winHandleBefore = driver.getWindowHandle();
driver.switchTo().window(winHandleBefore);
driver.findElement(By.id("txtEnterCptCode")).sendKeys("99219");
Now I have the next error:
Exception in thread "main" org.openqa.selenium.NoSuchElementException:
Unable to find element with id == txtEnterCptCode (WARNING: The server
did not provide any stacktrace information)
Command duration or timeout: 404 milliseconds.
Any ideas?
It seems like you are not actually switching to any new window. You are supposed get the window handle of your original window, save that, then get the window handle of the new window and switch to that. Once you are done with the new window you need to close it, then switch back to the original window handle. See my sample below:
i.e.
String parentHandle = driver.getWindowHandle(); // get the current window handle
driver.findElement(By.xpath("//*[#id='someXpath']")).click(); // click some link that opens a new window
for (String winHandle : driver.getWindowHandles()) {
driver.switchTo().window(winHandle); // switch focus of WebDriver to the next found window handle (that's your newly opened window)
}
//code to do something on new window
driver.close(); // close newly opened window when done with it
driver.switchTo().window(parentHandle); // switch back to the original window
I have an utility method to switch to the required window as shown below
public class Utility
{
public static WebDriver getHandleToWindow(String title){
//parentWindowHandle = WebDriverInitialize.getDriver().getWindowHandle(); // save the current window handle.
WebDriver popup = null;
Set<String> windowIterator = WebDriverInitialize.getDriver().getWindowHandles();
System.err.println("No of windows : " + windowIterator.size());
for (String s : windowIterator) {
String windowHandle = s;
popup = WebDriverInitialize.getDriver().switchTo().window(windowHandle);
System.out.println("Window Title : " + popup.getTitle());
System.out.println("Window Url : " + popup.getCurrentUrl());
if (popup.getTitle().equals(title) ){
System.out.println("Selected Window Title : " + popup.getTitle());
return popup;
}
}
System.out.println("Window Title :" + popup.getTitle());
System.out.println();
return popup;
}
}
It will take you to desired window once title of the window is passed as parameter. In your case you can do.
Webdriver childDriver = Utility.getHandleToWindow("titleOfChildWindow");
and then again switch to parent window using the same method
Webdriver parentDriver = Utility.getHandleToWindow("titleOfParentWindow");
This method works effectively when dealing with multiple windows.
Set<String> windows = driver.getWindowHandles();
Iterator<String> itr = windows.iterator();
//patName will provide you parent window
String patName = itr.next();
//chldName will provide you child window
String chldName = itr.next();
//Switch to child window
driver.switchto().window(chldName);
//Do normal selenium code for performing action in child window
//To come back to parent window
driver.switchto().window(patName);
I have a sample program for this:
public class BrowserBackForward {
/**
* #param args
* #throws InterruptedException
*/
public static void main(String[] args) throws InterruptedException {
WebDriver driver = new FirefoxDriver();
driver.get("http://seleniumhq.org/");
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
//maximize the window
driver.manage().window().maximize();
driver.findElement(By.linkText("Documentation")).click();
System.out.println(driver.getCurrentUrl());
driver.navigate().back();
System.out.println(driver.getCurrentUrl());
Thread.sleep(30000);
driver.navigate().forward();
System.out.println("Forward");
Thread.sleep(30000);
driver.navigate().refresh();
}
}
string BaseWindow = driver.CurrentWindowHandle;
ReadOnlyCollection<string> handles = driver.WindowHandles;
foreach (string handle in handles)
{
if (handle != BaseWindow)
{
string title = driver.SwitchTo().Window(handle).Title;
Thread.Sleep(3000);
driver.SwitchTo().Window(handle).Title.Equals(title);
Thread.Sleep(3000);
}
}
i was having some issues with windowhandle and tried this one. this one works good for me.
String parentWindowHandler = driver.getWindowHandle();
String subWindowHandler = null;
Set<String> handles = driver.getWindowHandles();
Iterator<String> iterator = handles.iterator();
while (iterator.hasNext()){
subWindowHandler = iterator.next();
driver.switchTo().window(subWindowHandler);
System.out.println(subWindowHandler);
}
driver.switchTo().window(parentWindowHandler);

How to Click a option in Security Warning dialog box using Selenium?

I've written a selenium code with java testng for submitting a form. After clicking submit button the page navigates to thankyou page. But before loading thankyou am getting a Security Warning dialog box which has the options called 'Continue' and 'Cancel'. How to click Continue through selenium control. There is no way for getting xpath or id of the continue button.
Had same problem, this worked for firefox 13 and selenium 2.0
Use spy to get the window info.
For firefox 13 windows class is MozillaDialogClass
WindowName is Security Warning.
declare import
[DllImport("user32.dll")]
public static extern int FindWindow(string className, string windowName);
make method
public static void SetOkButton(string className, string windowName)
{
int handle = FindWindow(className, windowName);
if (handle > 0)
{
if (SetForegroundWindow(handle))
{
SendKeys.SendWait("{ENTER}");
}
}
}
call the method
SetOkButton("MozillaDialogClass", "Security Warning");
Remember to add a wait before it appears otherwise your code may executed before alert actually appears. Following piece of code is working for me
private void acceptSecurityAlert() {
Wait<WebDriver> wait = new FluentWait<WebDriver>(driver).withTimeout(10, TimeUnit.SECONDS)
.pollingEvery(3, TimeUnit.SECONDS)
.ignoring(NoSuchElementException.class);
Alert alert = wait.until(new Function<WebDriver, Alert>() {
public Alert apply(WebDriver driver) {
try {
return driver.switchTo().alert();
} catch(NoAlertPresentException e) {
return null;
}
}
});
alert.accept();
}
If that is a JS confirmation box on load of the page, then (as the docs say), you can't do much. Selenium 2 (WebDriver) can handle these dialogs in a much better way:
driver.switchTo().alert().accept();
If that is a Firefox confirmation, you can't do anything with Selenium.
I'd give java.awt.Robot a try.
There is no xpath or id of the 'Continue' button on the 'Security Warning' dialog as this dialog is not a browser dialog. This dialog was generated by Java.
Selenium only automates browsers. Hence, it is beyond the scope of Selenium to click on the 'Continue' button.
Thankfully there is a way to click on the 'Continue' button by taking the help of these jars: jna.jar and jna-platform.jar and java.awt.Robot class.
If you don't know when 'Security Warning' will appear, you can write code to wait until the 'Security Warning' appears. This code keeps checking for the current active window title. Once 'Security Warning' dialog appears, the currently active window will become 'Security Warning' dialog. The code then uses TAB key to navigate to 'Continue' button and presses ENTER key.
You can use the below method after doing the necessary imports:
public void acceptSecurityAlert() {
//Keep checking every 7 seconds for the 'Security Warning'
Wait<WebDriver> wait = new FluentWait<WebDriver>(driver).withTimeout(1000, TimeUnit.SECONDS).pollingEvery(7, TimeUnit.SECONDS).ignoring(NoSuchElementException.class);
//Wait until the 'Security Warning' appears
boolean isTrue = wait.until(new Function<WebDriver, Boolean>(){
//implement interface method
public Boolean apply(WebDriver driver) {
try {
char[] buffer = new char[1024 * 2];
HWND hwnd = User32.INSTANCE.GetForegroundWindow();
User32.INSTANCE.GetWindowText(hwnd, buffer, 1024);
//System.out.println("Active window title: " + Native.toString(buffer));
//Check for 'Security Warning' window
if(Native.toString(buffer).equalsIgnoreCase("Security Warning")){
//After 'Security Warning' window appears, use TAB key to go to 'Continue' button and press ENTER key.
//System.out.println("Pressing keys...");
Robot robot = new Robot();
robot.keyPress(KeyEvent.VK_TAB); robot.delay(200);
robot.keyRelease(KeyEvent.VK_TAB); robot.delay(200);
robot.keyPress(KeyEvent.VK_TAB); robot.delay(200);
robot.keyRelease(KeyEvent.VK_TAB); robot.delay(200);
robot.keyPress(KeyEvent.VK_ENTER); robot.delay(200);
robot.keyRelease(KeyEvent.VK_ENTER); robot.delay(200);
return true;
}
return null;
}catch(Exception e) {
System.out.println("Exception!");
e.printStackTrace();
}
return null;
}
});
}

Categories

Resources