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

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);
}
}

Related

New Browser Tab Opens, Can't find WebELements after SELENIUM WEBDRIVER JAVA

I am running the following method:
public void AssertPreviousSubmissionClick() throws InterruptedException{
EnterLoginCredentials();
PreviousSubmissionClick(); //After this action takes place a new Browser Tab Opens
Assert.assertTrue("Clicking the link didn't work!",oldLogo.isDisplayed());
Reporter.log("PASSED! User Successfully click the Previous Year(s) Submission Request and was taken into the Grant Process!");
}
I left a note at PreviousSubmissionClick() at which point a new browser Tab is open. At this point in the method I can no longer identify WebElements on the new browser tab that opens. Please suggest how I can find WebElements on the new browser tab.
You need to switch the focus to the new tab
String currentTab = driver.getWindowHandle();
for (String tab : driver.getWindowHandles()) {
if (!tab.equals(currentTab)) {
driver.switchTo().window(tab);
}
}
// do something on new tab
And to close the new tab and switch back
driver.close();
driver.switchTo().window(currentTab);
Try this ,it will work.
public void handle(){
WebDriver driver;
driver=new FirefoxDriver();
driver.manage().window().maximize();
driver.get("http://toolsqa.com/automation-practice-switch-windows/");
driver.findElement(By.xpath(".//*[#id='content']/p[4]/button")).click();
ArrayList<String> tabs2 = new ArrayList<String> (driver.getWindowHandles());
driver.switchTo().window(tabs2.get(1));
System.out.println(driver.getTitle());
}

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);

selenium web driver - switch to parent window

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.

Categories

Resources