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.
Related
I'm trying to move to a different page (click 'my account'), and a floating advertisement appears:
advertisement
I tried to click on it, and can't find the "Close" element.
Found that it might related to frames, but still not works.
My Code:
public void clickMyAccount() {
driver.findElement(myAccountBtn).click();
driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(10));
driver.manage().timeouts().pageLoadTimeout(Duration.ofSeconds(10));
try {
Thread.sleep(5);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public void clickCloseAd(){
driver.switchTo().frame(driver.findElement(By.id("google_esf")));
driver.switchTo().frame(driver.findElement(By.id("aswift_9")));
driver.switchTo().frame(driver.findElement(By.id("ad_iframe")));
driver.findElement(By.id("dismiss-button")).click();
driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(10));
driver.manage().timeouts().pageLoadTimeout(Duration.ofSeconds(10));
driver.switchTo().defaultContent();
}
Site:
https://practice.automationtesting.in/
Any idea how can I click the floating advertisement?
Tried: move between frames until able to find the Close element
Actual: still can't find this element
It is hard to handle advertisement popUp. So we can handle it in 2 ways:
downloading ad-blocker extension to your chrome and using the chrome option code.
download ad-bocker- https://chrome.google.com/webstore/detail/adblock-%E2%80%94-best-ad-blocker/gighmmpiobklfepjocnamgkkbiglidom
use chromeoption driver code:
ChromeOptions chromeOptions = new ChromeOptions();
chromeOptions.addArguments("disable-infobars");
Notice that popUp gets disabled is do back. so we can is click on myaccount go back and then click back:
WebElement MyAccount = driver.findElement(By.xpath("//[#href='https://practice.automationtesting.in/my-account/']"));
MyAccount.click();
driver.navigate().back();
MyAccount.click();
Found the issue:
My 'wait' not always working, so the driver tries to close the ad when not displayed - still searching for a way to correct this
It's working without frame1: "google_esf", only frame2 and frame3 needed
Updated code:
public void clickMyAccount() {
System.out.println("Click My Account");
if(driver.findElement(myAccountBtn).isDisplayed()){
driver.findElement(myAccountBtn).click();
driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(10));
driver.manage().timeouts().pageLoadTimeout(Duration.ofSeconds(10));
} else {
System.out.println("My account button not displayed");
}
}
public void clickCloseAd(){
System.out.println("Click Close Ad");
if(driver.findElement(By.id("aswift_9")).isDisplayed()){
// driver.switchTo().frame(driver.findElement(By.id("google_esf"))); //Not in use but also a frame
driver.switchTo().frame(driver.findElement(By.id("aswift_9")));
driver.switchTo().frame(driver.findElement(By.id("ad_iframe")));
driver.findElement(By.id("dismiss-button")).click();
driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(10));
driver.manage().timeouts().pageLoadTimeout(Duration.ofSeconds(10));
driver.switchTo().defaultContent();
} else {
System.out.println("Ad not displayed");
}
}
Thanks all!
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);
}
}
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());
}
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'
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.