Handling Multiple Browser Windows in Selenium
In Selenium WebDriver, handling multiple browser windows involves switching
between different windows or tabs that the browser might open during a test
session. Here's how you can manage multiple browser windows:
1. Basic Concept
Every browser window or tab has a unique identifier known as a window
handle. Selenium provides methods to get the current window handle, get all
window handles, and switch between windows using these handles.
2. Key Methods
getWindowHandle(): Returns a string representing the current window handle.getWindowHandles(): Returns a set of strings representing all window handles.switchTo().window(String handle): Switches the focus to the specified window.
package AlertFrameWindowsBasics;
import java.util.Iterator;
import java.util.Set;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class MultipleBrowserWindosHandling1 {
public static
void main(String[] args) throws InterruptedException {
System.setProperty("webdriver.chrome.driver",
".\\Drivers\\chromedriver.exe");
// .
Represents current project folder name
// //open chrome browser
WebDriver driver =
new ChromeDriver();
//
get("url ") - to open the url in chrome browser
driver.get("file:///C:/brahma/Practise/qtp%20practise/web%20apps/ALL%20Web%20objects.html");
//*************************************
//click
'Open Login form' button - it opens new window - browser -2
driver.findElement(By.id("loginid")).click();
Thread.sleep(5000);
//
get browsers count
Set<String>
allBrowserWndAddresses = driver.getWindowHandles();
// can be used to get all the browser window
addresses and store into Set object i.e allBrowserWndAddresses
int
browsersCnt= allBrowserWndAddresses.size();
System.out.println("browsersCnt="+browsersCnt);//
browsersCnt=2
//
switch to new browser window i.e
window-2
// driver.switchTo().window("browser-2
addres");
//
get browser-1 address
Iterator<String> it =allBrowserWndAddresses.iterator();
String
browser1Address = it.next();
System.out.println("browser1Address="+browser1Address);
//
get browser-2 address
String
browser2Address= it.next();
System.out.println("browser2Address="+browser2Address);
//
alert -->
//
frame -->frame("");
//
Switch to browser -2
//
Window("browser window address")
driver.switchTo().window(browser2Address);
//enter
'ramu' in un textbox userid
driver.findElement(By.id("userid")).sendKeys("Ramu");
//enter
'mercury' in password -pwdid
driver.findElement(By.id("pwdid")).sendKeys("mercury");
Thread.sleep(5000);
// close browser -2 window
//
close the browser which is currently focussed
// //
it will close currently focussed browser window i.e browser-2
driver.close();
//
browser -1 or browser2 ??? close browser-2
// switch to Main page i.e Browser -1
driver.switchTo().window(browser1Address);
//
enter 'Rao' in last name -lastname
driver.findElement(By.name("lastname")).sendKeys("Rao");
Thread.sleep(5000);
// switch to invalid browser address by passing
invalid address
// driver.switchTo().window("Abcddfsfa");
// org.openqa.selenium.NoSuchWindowException: no
such window
// there is no ele present --> NoSuchElementException
//
no alert --> NoAlertPresentException
// Frame is not there -->
NoSuchFrameException
// Window -->
NoSuchWindowException
}
}
-
// HW open AllWeboebjects.html page, click 'Webtable'all button and it opens new window and
Switch to new window and
get table count, close browser2 i.e
Webtableall.html page.
Go to Browser-1 and enter some value in "password"
text box
---------------------------------------
*** FAQ how can you handle multiple browser windows ?
Q: Open 3 browser windows and get all browser Titles ?
package AlertFrameWindowsBasics;
import java.util.Iterator;
import java.util.Set;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class GetAllBrowserTitles {
public static
void main(String[] args) throws InterruptedException {
System.setProperty("webdriver.chrome.driver",
".\\Drivers\\chromedriver.exe");
// .
Represents current project folder name
// //open chrome browser
WebDriver driver =
new ChromeDriver();
//
get("url ") - to open the url in chrome browser
driver.get("file:///C:/brahma/Practise/qtp%20practise/web%20apps/ALL%20Web%20objects.html");
//click
'Open Login form' button - it opens new window - browser -2
driver.findElement(By.id("loginid")).click();
Thread.sleep(4000);
//
click 'webtable all' button - it opens new window - browser -3 -allid
driver.findElement(By.id("allid")).click();
Thread.sleep(4000);
//
click 'Simple allObjects' button simpleid
- it opens new window - browser -4 -simpleid
driver.findElement(By.id("simpleid")).click();
Thread.sleep(4000);
//
get all browsers Count
Set<String>
allWindowAddresses = driver.getWindowHandles();
System.out.println("browsersCnt="
+allWindowAddresses.size());
//All
browser count =4
//
get all browser windows addresses using iterator() using while loop
Iterator<String> it = allWindowAddresses.iterator();
//
br1 br2 - 3 4
while(it.hasNext())
{
String address = it.next();
driver.switchTo().window(address);
String title = driver.getTitle();
System.out.println("title="+title);
}
//
switch to each browser
//
get title
// title=All
webobjects MyTitle Sumanth
// title=Simple
all objects Title
// title=WebtableAll
Title
// title=Login
page
//HW get all browser titles using for each loop
System.out.println("get all browser titles
using for each loop************************");
// title=All webobjects
MyTitle Sumanth
// title=Simple
all objects Title
// title=WebtableAll
Title
// title=Login
page
}
}
HW :WAP to develop a resuable method to close browser based on given title
closeBrowserBasedOngivenTitle("Login page");
closeBrowserBasedOngivenTitle("WebtableAll Title");
Code:
HW WAP to develop a seperate a method to Close all browser windows
except 'Login page' title -2nd way for
each loop ?
public static void closeAllBrowsersExceptGivenTitle(String
expTitle)
{
}
Open 3 browser windows , Develop
resusable method to switch to Window Based on title name ?
switchToBrowserBasedOnGivenTitle(String title)
{
}
switchToBrowserBasedOnGivenTitle("Login page");
switchToBrowserBasedOnGivenTitle("WebtableAll Title");
package AlertFrameWindowsBasics;
import java.util.Iterator;
import java.util.Set;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class SwitchToBrowserBasedOnTitlle {
int a;// def val for instance var -0
float f; // 0.0
String s;// null
static WebDriver
driver;// null
//Develop switchToBrowserBasedOnGivenTitle("Login
page")
public static
void switchToBrowserBasedOnGivenTitle(String title)
{
System.out.println("driver="+
driver);// nul;;
Set<String>
allBrowserWndAddresses = driver.getWindowHandles();
// null. --> NullpointerException
boolean
TitleFound = false;
Iterator<String> it = allBrowserWndAddresses.iterator();
while(it.hasNext())
{
String
address =it.next();
driver.switchTo().window(address);
String
actualTitle = driver.getTitle();
if(title.equals(actualTitle))
{
System.out.println("title is found
="+ title);
TitleFound = true;
break;
}
}
if(TitleFound
== true)
{
System.out.println("title
is found ="+ title);
}
else
{
System.out.println("title
=" +title +" is not found. Plz give valid/ correct title");
}
}
public static
void main(String[] args) throws InterruptedException {
System.setProperty("webdriver.chrome.driver",
".\\Drivers\\chromedriver.exe");
// .
Represents current project folder name
// //open chrome browser
// WebDriver driver =
new ChromeDriver();
driver
= new ChromeDriver();
//
get("url ") - to open the url in chrome browser
driver.get("file:///C:/brahma/Practise/qtp%20practise/web%20apps/ALL%20Web%20objects.html");
//click
'Open Login form' button - it opens new window - browser -2
driver.findElement(By.id("loginid")).click();
Thread.sleep(4000);
//
click 'webtable all' button - it opens new window - browser -3
driver.findElement(By.id("allid")).click();
Thread.sleep(4000);
//
click 'Simple allObjects' button
simpleid - it opens new window - browser -4
driver.findElement(By.id("simpleid")).click();
Thread.sleep(4000);
//
Call switchtoWindow() by passing -Login page
switchToBrowserBasedOnGivenTitle("
Login page ");
//
Enter user . pwd
driver.findElement(By.id("userid")).sendKeys("Ramu");
driver.findElement(By.id("pwdid")).sendKeys("mercury");
//
close browser
driver.close();
//HW Switch to Window with title- All webobjects
MyTitle Sumanth
// HW
Enter first name, last name
// HW close
browser
//HW Go to
browser with title = Simple all objects
Title
// HW
Select 'Honda in bikes dropdown
// If
given title- is not found for browser?
switchToBrowserBasedOnGivenTitle("My
Login title");
}
}
FAQ Difference between GetWindowHandle() and
GetWindowHandles()?
|
Feature |
getWindowHandle() |
getWindowHandles() |
|
Purpose |
Retrieve
the handle of the current window |
Retrieve
the handles of all open windows |
|
Return
Type |
String |
Set<String> |
|
Number
of Handles Returned |
Single
handle |
Multiple
handles |
|
Common
Usage |
Store
or switch back to the current window |
Iterate
through and switch between multiple windows |
|
Example
Use Case |
Handling
a single window |
Handling
multiple windows, such as when a new tab is opened |
String GetWindowHandle()
can be used to get currently focussed browser window address
return type String
GetWindowHandles() -can be
used to get all browser window addresses
return
type set<String>
HW Develop resuable method to
closeAllBrowserWindows();
closeAllBrowserWindows()
{
// code
// code
}
Call:
closeAllBrowserWindows();
-------------------------------------------
HW WAP to open 2 browser
windows ,
Switch to browser 2 by passing browser number i.e 2
SwicthToBrowser(int browserNo)
{
}
SwicthToBrowser(2);
SwicthToBrowser(1);
FAQ where did u use Method overloading (polymorphism) in ur
project ?
SwitchToBrowser(int browserno)
{
}
SwitchToBrowser(String title)
{
}
HW WAP to open 2 browser
windows ,
close browser 2 by passing browser number i.e 2
CloseBrowser(int browserNo)
{
}
CloseBrowser(2);
CloseBrowser(1);
FAQ how can you handle multiple tabs/ browser windows?
Same code ..
HW WAP to get all browser
titles and addresss , store into
hashmap<String,String> and
return hashmap, display title and address?
//HW Handle -ve scenario-
if given browser title is not there, display proper msg "Given browser is
not found with given title=" while
closing browser based on given title ="
ex: closeBrowserByTitle("Login page Form 123");
// if title =Login page
Form 123 is not available , display proper msg ?
No comments:
Post a Comment