Selenium Get popup and popunder currently open link - java

In my site when I search anything on homepage its open one leaves behind window and one popunder window.Using selenium I want to know its open correctly or not and also take this two window link.
I tried this but it's not working
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;
}
}

When you've launched only one WebDriver process, there will be only one WebDriver. It contains a list of window handles. You don't need to have multiple instances of WebDriver. If you want to go to the new window (or tab) and then go back to the main window, you should store the windowHandle of the main window somewhere in the WebDriverInitialize class. My example below shows how to store the windowHandle in the Utility class.
public class Utility
{
public static void switchToNewWindow(String title){
Set<String> windowIterator = WebDriverInitialize.getDriver().getWindowHandles();
System.err.println("No of windows : " + windowIterator.size());
for (String s : windowIterator) {
String windowHandle = s;
WebDriverInitialize.getDriver().switchTo().window(windowHandle);
System.out.println("Window Title : " + WebDriverInitialize.getDriver().getTitle());
System.out.println("Window Url : " + WebDriverInitialize.getDriver().getCurrentUrl());
// you may use .getTitle().contains(title) if you cannot predict the full title
if (WebDriverInitialize.getDriver().getTitle().equals(title) ){
break;
}
}
}
public static string mainWindowHandle;
}
WebDriverInitialize.getDriver().get("https://www.rentalhomes.com/");
Utility.mainWindowHandle = WebDriverInitialize.getDriver().getWindowHandle();
...
WebDriverInitialize.getDriver().findElement(By.id("home-page-search-btn")).click();
// Switch to the new window
Utility.switchToNewWindow("San Francisco ...");
// Switch back to main window
WebDriverInitialize.getDriver().switchTo().window(Utility.mainWindowHandle);

Related

I have tried to copy URL which is opened in new tab but copying old tab urls. How to copy new tab url java selenium?

How to copy new tab url java selenium?
'package TestCases;
public class Learn_TC3 extends SuperTestScript
{
#Test
public void LoginTC1() throws Exception
{
//all the required data
String USRID = ExcelLibrary.readData("Sheet1", 0, 0);
String PSW = ExcelLibrary.readData("Sheet1", 0, 1);
//create page objects
LearnPage Lp = new LearnPage();
Tabswitch Ts = new Tabswitch();
//invoke the methods
Lp.ClickonMaterialsButton();
Thread.sleep(3000);
Lp.ClickonPDF1();//By clicking on pdf. Pdf opens in new tab
String CurrentUrl = driver.getCurrentUrl();// to Fetch new url
ExcelLibrary.writeData("Sheet1", 0, 4, CurrentUrl);//write url to excel sheet?
Ts.switchToPreviousTabAndClose(); //Closing new tab
}
}'
I have tried to copy URL which is opened in new tab but copying old tab urls. How to copy new tab url java selenium?
After clicking on Lp.ClickonPDF1() that opens a new tab you have to switch Selenium driver to the opened tab in order to perform actions there.
So your code can be something like this:
Lp.ClickonMaterialsButton();
Thread.sleep(3000);
Lp.ClickonPDF1();//By clicking on pdf. Pdf opens in new tab
Thread.sleep(500);
List<String> tabs = new ArrayList<>(driver.getWindowHandles());
driver.switchTo().window(tabs.get(tabs.size()-1));
String CurrentUrl = driver.getCurrentUrl();// to Fetch new url
ExcelLibrary.writeData("Sheet1", 0, 4, CurrentUrl);//write url to excel sheet?
Ts.switchToPreviousTabAndClose(); //Closing new tab
Not sure how can I use the driver object in your infrastructure, so I used it as regular, with no relation to any page object instance.
Below are methods that I created for a test project (using cucumber-java and selenium-java) that is similar to your approach, where it was required to:
Click on a link for a pdf document on a webpage, which opened in a new tab
List the opened tabs
Move to the new tab
Get the url for the pdf document and verify (assert) that it was correct
Close the pdf tab
Return to the webpage
Feel free to use what you need
#Then("^on \"([^\"]*)\" I can view the Pdf Document of \"([^\"]*)\"$")
public void on_I_can_view_the_Pdf_Document_of(String relativeUrl, String document) throws Throwable {
viewPDFDocument(relativeUrl, document);
}
private void viewPdfDocument(String relativeUrl, String document) throws Exception {
clickOnLink("", document);
verifyPdfUrl();
}
public void clickOnLink(String linkXpath, String label) throws Exception {
LOG.info("Clicking link '{}' with xpath '{}'", label, linkXpath);
retryIfAssertionFails(() -> {
String xpath = linkXpath + "//a/descendant-or-self::*[contains(normalize-space(text()), '" + label + "')]";
waitForElementToBeClickable(xpath);
driver.findElementByXPath(xpath).click();
return null;
});
LOG.info("Link clicked");
sleep(50);
}
private void verifyPdfUrl() throws Exception {
String parentWindowHandle = driver.getWindowHandle();
WebDriverWait wait = new WebDriverWait(driver, 5);
wait.until(ExpectedConditions.numberOfWindowsToBe(2));
for (String windowHandle : driver.getWindowHandles()) {
if (!windowHandle.equals(parentWindowHandle)) {
driver.switchTo().window(windowHandle);
}
}
String pdfTabUrl;
pdfTabUrl = driver.getCurrentUrl();
assertTrue(pdfTabUrl.contains(
"/app/restrict/application/caseInformation.pdf")); {
System.out.println("Correct url presented: " + pdfTabUrl);
}
if (!driver.getWindowHandle().equals(parentWindowHandle)) {
driver.close();
}
driver.switchTo().window(parentWindowHandle);
}
In your case it is updating to the following:
Lp.ClickonMaterialsButton();
Thread.sleep(3000);
Lp.ClickonPDF1();//By clicking on pdf. Pdf opens in new tab
String parentWindowHandle = driver.getWindowHandle();
WebDriverWait wait = new WebDriverWait(driver, 5);
wait.until(ExpectedConditions.numberOfWindowsToBe(2));
for (String windowHandle : driver.getWindowHandles()) {
if (!windowHandle.equals(parentWindowHandle)) {
driver.switchTo().window(windowHandle);
}
}
String pdfTabUrl;
pdfTabUrl = driver.getCurrentUrl(); // to Fetch new url
ExcelLibrary.writeData("Sheet1", 0, 4, pdfTabUrl); //write url to excel sheet?
if (!driver.getWindowHandle().equals(parentWindowHandle)) {
driver.close();
} //Closing new tab
driver.switchTo().window(parentWindowHandle); //Switch back to original tab
You can do that pretty easily with Selenium 4
Code:
driver.get("https://www.google.com");
driver.switchTo().newWindow(WindowType.TAB);
driver.navigate().to("https://www.stackoverflow.com");
System.out.println(driver.getCurrentUrl());
Output:
https://stackoverflow.com/
You can do like below with your code,
Lp.ClickonPDF1();
driver.switchTo().newWindow(WindowType.TAB);
String CurrentUrl = driver.getCurrentUrl();

Opening a new tab and trying to scroll down the page and clicking on a link fails in Firefox browser

I have this function where I am trying to scroll down the page and click on a link. I have put the code in a for loop because I want to open more than one tab.
The links which I am trying to click are out of view of the window and they are in footer which is common for all the web pages. My method is supposed to scroll down till the link to be clicked is visible and then control + click and open a new tab. The method works perfectly well in Chrome and Internet Explorer browsers but fails in Firefox saying that the link to be clicked is not present. I think it is not scrolling down despite my putting code to scroll down. Please help.
public static void checkHrefsWithBrowserUrls(List<WebElement> links)
{
String parentTab = null;
String clickOnLink = Keys.chord(Keys.CONTROL, Keys.ENTER);
log.debug("Checking that the links open the correct url");
for (WebElement link : links) {
((JavascriptExecutor)driver)
.executeScript("arguments[0].scrollIntoView(true);", link);
String href = link.getAttribute("href");
link.sendKeys(clickOnLink);
WaitUtilities.sleep(1L);
Iterator<String> handleIterator = driver.getWindowHandles().iterator();
parentTab = handleIterator.next();
if(handleIterator.hasNext()) {
driver.switchTo().window(handleIterator.next());
WaitUtilities.waitForUrlToBe(url());
if(!href.equals(url())) {
log.error("Link(s) opening wrong URL(s): " + url());
}
driver.close();
driver.switchTo().window(parentTab);
}
}
driver.switchTo().window(parentTab);
}
Here is the pseudo code to handle the state element issue.
public static void checkHrefsWithBrowserUrls(String xpath)
{
String parentTab = null;
String clickOnLink = Keys.chord(Keys.CONTROL, Keys.ENTER);
log.debug("Checking that the links open the correct url");
int linksCount = driver.findElements(By.xpath(xpath)).size();
for (int linkCounter=1; linkCounter=linksCount, linkCounter++) {
link = driver.findElements(By.xpath(xpath)).get(linkCounter)
((JavascriptExecutor)driver)
.executeScript("arguments[0].scrollIntoView(true);", link);
String href = link.getAttribute("href");
link.sendKeys(clickOnLink);
WaitUtilities.sleep(1L);
Iterator<String> handleIterator = driver.getWindowHandles().iterator();
parentTab = handleIterator.next();
if(handleIterator.hasNext()) {
driver.switchTo().window(handleIterator.next());
WaitUtilities.waitForUrlToBe(url());
if(!href.equals(url())) {
log.error("Link(s) opening wrong URL(s): " + url());
}
driver.close();
driver.switchTo().window(parentTab);
}
}
driver.switchTo().window(parentTab);
}

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