How to switch to newly opened tab and close it? - selenium

I have used the below two methods to switch to the tab and close it.But unfortunately, none of them are useful.Please provide alternate methods.
sol1:
public static void switchTab()
{
try{
webDriver.findElement(By.cssSelector("body")).sendKeys(Keys.CONTROL, Keys.PAGE_DOWN);
webDriver.close();
webDriver.findElement(By.cssSelector("body")).sendKeys(Keys.CONTROL, Keys.PAGE_DOWN);
}
catch(Exception e){
e.printStackTrace();}
}
}
Here, driver is closing the whole browser instead of closing the tab.
sol2:
public void switchTab(){
try{
ArrayList<String> tabs2 = new ArrayList<String> (webDriver.getWindowHandles());
webDriver.switchTo().window(tabs2.get(1));
webDriver.close();
webDriver.switchTo().window(tabs2.get(0));
}
catch(Exception e){
e.printStackTrace();}
}
This is throwing index out of bounds exception as there is no other window opened.

Try below code
String homeWindow = driver.getWindowHandle();
Set<String> allWindows = driver.getWindowHandles();
//Use Iterator to iterate over windows
Iterator<String> windowIterator = allWindows.iterator();
//Verify next window is available
while(windowIterator.hasNext()){
//Store the Recruiter window id
String childWindow = windowIterator.next();
//Here we will compare if parent window is not equal to child window
if (homeWindow.equals(childWindow)){
driver.switchTo().window(childWindow);
//switch here to your desired window/tab and perform your action
driver.close();
}
Hope it will help you :)

If Understand correctly then, this will might help
put this in function block.
WebDriver driver = new FirefoxDriver();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.manage().window().maximize();
driver.get("http://google.com");
String gettitle = driver.getTitle();
String windowHandel = driver.getWindowHandle();
System.out.println(windowHandel + " " + gettitle);
driver.findElement(By.cssSelector("body")).sendKeys(Keys.CONTROL+"t");
ArrayList tabs = new ArrayList(driver.getWindowHandles());
System.out.println(tabs.size());
driver.switchTo().window((String) tabs.get(0));
gettitle ="";
driver.get("http://bing.com");
gettitle = driver.getTitle();
System.out.println(tabs.get(0).toString() + " " + gettitle);
driver.switchTo().window(windowHandel);
Thread.sleep(3000);
Actions actionObj = new Actions(driver);
actionObj.keyDown(Keys.CONTROL)
.sendKeys(Keys.chord("w"))
.keyUp(Keys.CONTROL)
.perform();
driver.switchTo().defaultContent();

Related

How to check all opened windows with title in chrome using selenium

In chrome 3 windows opened but without closing any window need to check last open window title
tried driver.getTitle();
but It returns first window title
Reason is that I want get page title and performing any activity on last window.
First you can switch the window and then validate page. You can try this approach:
public void switchwindow() throws InterruptedException {
currentHandle = driver.getWindowHandle();
WebDriverWait wait = new WebDriverWait(driver, 20);
wait.until(ExpectedConditions.numberOfWindowsToBe(2));
Set<String> allHandles = driver.getWindowHandles();
for (String handle : allHandles) {
if (!handle.equals(currentHandle)) {
driver.switchTo().window(handle);
break;
} else {
driver.switchTo().window(currentHandle);
Thread.sleep(8000);
}
}
}
Switch to parent window:
public void switchToParentWindow() throws InterruptedException {
Thread.sleep(5000);
driver.switchTo().window(currentHandle);
}

Selenium can't locate/read elements when browser extension (crumbs.crx) GPC is ON and it automatically opens new child window (which is should not)

Selenium can't locate/read elements when browser extension (crumbs.crx) GPC is ON and it automatically opens new child window (which is should not), I can switch to child window and can send tab keys but unable to locate/find the elements in which I should be able to input text/data. Any inputs are appreciated. Thanks in advance.
Switch window code:
public void switchWindow() {
String mainwindow = driver.getWindowHandle();
Set<String> s1 = driver.getWindowHandles();
Iterator<String> i1 = s1.iterator();
while (i1.hasNext()) {
String ChildWindow = i1.next();
if (!mainwindow.equalsIgnoreCase(ChildWindow)) {
driver.switchTo().window(ChildWindow);
String pageTitle=driver.getTitle();
log.info("Page title " + pageTitle);
driver.close();
System.out.println("Child window closed");
}
}
driver.switchTo().window(mainwindow);
String pageTitle=driver.getTitle();
log.info("Page title " + pageTitle);
}
Loading browser extension code:
public void loadBrowserExtension(String fileName) {
boolean remote = Boolean.getBoolean("remote");
ChromeOptions options = new ChromeOptions();
options.addExtensions(new File(Common_Page.class
.getResource("/data/testdata/" + fileName).getPath()));
if (remote) {
driver = driverUtil.getSeleniumGridDriver(options);
} else {
WebDriverManager.chromedriver().setup();
driver = new ChromeDriver(options);
}
driver.manage().timeouts().implicitlyWait(3L, TimeUnit.SECONDS);
driver.manage().window().setSize(new Dimension(1366, 768 + 45));
log.info("****** Screen Size: " + driver.manage().window().getSize() + "******");
DriverFactory.destroyDriver();
WaitUtils.waitSleep(10000);
WaitUtils.updateDriver(driver);
driverUtil.setDriver(driver);

Selenium webdriver switchin tab

I am unable to open google in new tab please review this code :
public static void main (String [] args) throws InterruptedException, AWTException
{
System.setProperty("webdriver.chrome.driver","C://Users//vbisht//Downloads//chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.navigate().to("https://www.google.co.in/");
Robot r = new Robot();
r.keyPress(KeyEvent.VK_CONTROL);
r.keyPress(KeyEvent.VK_T);
//Thread.sleep(10000);
//driver.navigate().refresh();*/
ArrayList<String> tabs = new ArrayList<String> (driver.getWindowHandles());
driver.switchTo().window(tabs.get(1)); //switches to new tab
driver.navigate().to("https://www.google.co.in/");
String parentWindowHandler=driver.getWindowHandle();// Store your parent window
String subWindowHandler = null;
Set<String> handles = driver.getWindowHandles(); // get all window handles
Iterator<String> iterator = handles.iterator();
while (iterator.hasNext()){
subWindowHandler = iterator.next();
}
driver.switchTo().window(subWindowHandler); // switch to popup window
Hope it will help you.
Try the below code,
The code below will open the link in new Tab.
String selectLinkOpeninNewTab = Keys.chord(Keys.CONTROL,Keys.RETURN);
driver.findElement(By.linkText("urlLink")).sendKeys(selectLinkOpeninNewTab);
The code below will open empty new Tab.
String selectLinkOpeninNewTab = Keys.chord(Keys.CONTROL,"t");
driver.findElement(By.linkText("urlLink")).sendKeys(selectLinkOpeninNewTab);
Instead of using Robot Class, You can simply open it with Javascript Executor
public static void main (String [] args) throws InterruptedException, AWTException { System.setProperty("webdriver.chrome.driver","C://Users//vbisht//Downloads//chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.navigate().to("https://www.google.co.in/");
((JavascriptExecutor) driver).executeScript("window.open()");
ArrayList<String> tabs = new ArrayList<String> (driver.getWindowHandles());
driver.switchTo().window(tabs.get(1)); //switches to new tab
driver.navigate().to("https://www.google.co.in/");
}
To open two different urls in two different TABs, once you initiate opening a new tab/window you have to induce WebDriverWait and then collect the window handles and finally iterate through the window handles and then switchTo().window(newly_opened) as per the following example:
Sample Code:
System.setProperty("webdriver.chrome.driver", "C:\\Utility\\BrowserDrivers\\chromedriver.exe.exe");
WebDriver driver = new InternetExplorerDriver();
driver.get("http://www.google.com");
String first_tab = driver.getWindowHandle();
System.out.println("Working on Google");
((JavascriptExecutor) driver).executeScript("window.open('http://facebook.com/');");
WebDriverWait wait = new WebDriverWait(driver,5);
wait.until(ExpectedConditions.numberOfWindowsToBe(2));
Set<String> s1 = driver.getWindowHandles();
Iterator<String> i1 = s1.iterator();
while(i1.hasNext())
{
String next_tab = i1.next();
if (!first_tab.equalsIgnoreCase(next_tab))
{
driver.switchTo().window(next_tab);
System.out.println("Working on Facebook");
}
}
Console Output:
Working on Google
Working on Facebook

How to use clickandwait in Selenium Webdriver using Java?

I am trying to click on the object, to show the list of value pop-up.
I used the following script, but unable to populate the list value pop-up.
Driver.findElement(By.xpath(OR.getProperty(Object))).click();
Thread.sleep(1000L);
Is there any other way to click and wait for the object?
Driver.findElement(By.xpath(OR.getProperty(Object))).click();
WebDriverWait wait = new WebDriverWait(Driver, timeoutInSeconds);
wait.until(ExpectedConditions.elementToBeClickable(By.id("yourId")));
There are other conditions like visibilityOf so choose the one which suits you most - documentation here.
String mainWindowHandle = driver.getWindowHandle();
System.out.println(mainWindowHandle);
wait.until(ExpectedConditions.elementToBeClickable(By.xpath(OR.getProperty(Object)));
Driver.findElement(By.xpath(OR.getProperty(Object))).click();
PageUtil.sleep(3000);
Set<String> s1 = driver.getWindowHandles();
Iterator<String> ite = s1.iterator();
while (ite.hasNext()) {
String popupHandle = ite.next().toString();
System.out.println(popupHandle + " Present Pop Up window name");
if (!popupHandle.contains(mainWindowHandle)) {
driver.switchTo().window(popupHandle);
}
}
WebDriverWait wait = new WebDriverWait(Driver, timeoutInSeconds);
wait.until(ExpectedConditions.elementToBeClickable(By.id("yourId")));
Driver.findElement(By.id("yourId")).click();
driver.switchTo().window(mainWindowHandle);
After clicking you can wait using FluentWait,
// Waiting 30 seconds for an element to be present on the page, checking
// for its presence once every 5 seconds.
Wait<WebDriver> wait = new FluentWait<WebDriver>(driver)
.withTimeout(30, SECONDS)
.pollingEvery(5, SECONDS)
.ignoring(NoSuchElementException.class);
WebElement foo = wait.until(new Function<WebDriver, WebElement>() {
public WebElement apply(WebDriver driver) {
return driver.findElement(By.id("foo"));
}
});
refer this for more info
I'm not quite familiar with java syntax, but I'll give you php code and you can write similar. The idea is to find HTML element by tag and get it's id BEFORE YOU CLICK. Then AFTER THE CLICK wait for the id to change.
It looks like this:
class MySeleniumCondition extends WebDriverExpectedCondition{
public static function htmlElementIdIsNot($htmlElementId) {
return new WebDriverExpectedCondition(
function ($driver) use ($htmlElementId) {
$htmlElement = $driver->findElement(WebDriverBy::tagName('html'));
return $htmlElementId != $htmlElement->getId();
}
);
}
}
// .............. somehere in a class:
public function waitForNewPage($oldHtmlElementId, $time = 10){
try{
$this->driver->wait($time)->until(
MySeleniumCondition::htmlElementIdIsNot(
$oldHtmlElementId
)
);
return true;
}catch(TimeOutException $e){
return false;
}
}
// use this only when you are sure the page will reload
public function clickAndWait(WebDriverBy $locator, $time = 10){
$webElement = $this->driver->findElement($locator);
$oldHtmlElement = $driver->findElement(WebDriverBy::tagName('html'));
$oldHtmlElementId = $oldHtmlElement->getId();
$webElement->click();
$this->waitForNewPage($oldHtmlElementId, $time);
return true;
}

How to deal with ModalDialog using selenium webdriver?

I am unable to switch to Modal Dialog of given example
http://samples.msdn.microsoft.com/workshop/samples/author/dhtml/refs/showModalDialog2.htm
I don't know how to get element on modal Dialog
Use
following methods to switch to modelframe
driver.switchTo().frame("ModelFrameTitle");
or
driver.switchTo().activeElement()
Hope this will work
What you are using is not a model dialog, it is a separate window.
Use this code:
private static Object firstHandle;
private static Object lastHandle;
public static void switchToWindowsPopup() {
Set<String> handles = DriverManager.getCurrent().getWindowHandles();
Iterator<String> itr = handles.iterator();
firstHandle = itr.next();
lastHandle = firstHandle;
while (itr.hasNext()) {
lastHandle = itr.next();
}
DriverManager.getCurrent().switchTo().window(lastHandle.toString());
}
public static void switchToMainWindow() {
DriverManager.getCurrent().switchTo().window(firstHandle.toString());
Try the below code. It is working in IE but not in FF22. If Modal dialog found is printed in Console, then Modal dialog is identified and switched.
public class ModalDialog {
public static void main(String[] args) throws InterruptedException {
// TODO Auto-generated method stub
WebDriver driver = new InternetExplorerDriver();
//WebDriver driver = new FirefoxDriver();
driver.get("http://samples.msdn.microsoft.com/workshop/samples/author/dhtml/refs/showModalDialog2.htm");
String parent = driver.getWindowHandle();
WebDriverWait wait = new WebDriverWait(driver, 10);
WebElement push_to_create = wait.until(ExpectedConditions
.elementToBeClickable(By
.cssSelector("input[value='Push To Create']")));
push_to_create.click();
waitForWindow(driver);
switchToModalDialog(driver, parent);
}
public static void waitForWindow(WebDriver driver)
throws InterruptedException {
//wait until number of window handles become 2 or until 6 seconds are completed.
int timecount = 1;
do {
driver.getWindowHandles();
Thread.sleep(200);
timecount++;
if (timecount > 30) {
break;
}
} while (driver.getWindowHandles().size() != 2);
}
public static void switchToModalDialog(WebDriver driver, String parent) {
//Switch to Modal dialog
if (driver.getWindowHandles().size() == 2) {
for (String window : driver.getWindowHandles()) {
if (!window.equals(parent)) {
driver.switchTo().window(window);
System.out.println("Modal dialog found");
break;
}
}
}
}
}
Solution in R (RSelenium):
I had a popup dialog (which is dynamically generated) and hence undetectable in the original page source code
Here are methods which worked for me:
Method 1: Simulating Pressing keys for Tabs and switching to that modal dialog
My current key is focussed on a dropdown button behind the modal dialog box
remDr$sendKeysToActiveElement(list(key = "tab"))
Sys.sleep(5)
remDr$sendKeysToActiveElement(list(key = "enter"))
Sys.sleep(15)
Method 2: Bring focus to the frame(or iframe) if you can locate it
date_filter_frame <- remDr$findElement(using = "tag name", 'iframe')
date_filter_frame$highlightElement()
Sys.sleep(5)
remDr$switchToFrame(date_filter_frame)
Sys.sleep(2)
Now you can search for elements in the frame. Remember to put adequate Sys.sleep in between commands for elements to load properly (just in case)
date_filter_element <- remDr$findElement(using = "xpath", paste0("//*[contains(text(), 'Week to Date')]"))
date_filter_element$highlightElement()
Try this code, include your object names & variable to work.
Set<String> windowids = driver.getWindowHandles();
Iterator<String> iter= windowids.iterator();
for (int i = 1; i < sh.getRows(); i++)
{
while(iter.hasNext())
{
System.out.println("Main Window ID :"+iter.next());
}
driver.findElement(By.id("lgnLogin_UserName")).clear();
driver.findElement(By.id("lgnLogin_UserName")).sendKeys(sh.getCell(0,
i).getContents());
driver.findElement(By.id("lgnLogin_Password")).clear();
driver.findElement(By.id("lgnLogin_Password")).sendKeys(sh.getCell(1,
i).getContents());
driver.findElement(By.id("lgnLogin_LoginButton")).click();
Thread.sleep(5000L);
windowids = driver.getWindowHandles();
iter= windowids.iterator();
String main_windowID=iter.next();
String tabbed_windowID=iter.next();
System.out.println("Main Window ID :"+main_windowID);
//switch over to pop-up window
Thread.sleep(1000);
driver.switchTo().window(tabbed_windowID);
System.out.println("Pop-up window Title : "+driver.getTitle());
I have tried it, it works for you.
String mainWinHander = webDriver.getWindowHandle();
// code for clicking button to open new window is ommited
//Now the window opened. So here reture the handle with size = 2
Set<String> handles = webDriver.getWindowHandles();
for(String handle : handles)
{
if(!mainWinHander.equals(handle))
{
// Here will block for ever. No exception and timeout!
WebDriver popup = webDriver.switchTo().window(handle);
// do something with popup
popup.close();
}
}
Assuming the expectation is just going to be two windows popping up (one of the parent and one for the popup) then just wait for two windows to come up, find the other window handle and switch to it.
WebElement link = // element that will showModalDialog()
// Click on the link, but don't wait for the document to finish
final JavascriptExecutor executor = (JavascriptExecutor) driver;
executor.executeScript(
"var el=arguments[0]; setTimeout(function() { el.click(); }, 100);",
link);
// wait for there to be two windows and choose the one that is
// not the original window
final String parentWindowHandle = driver.getWindowHandle();
new WebDriverWait(driver, 60, 1000)
.until(new Function<WebDriver, Boolean>() {
#Override
public Boolean apply(final WebDriver driver) {
final String[] windowHandles =
driver.getWindowHandles().toArray(new String[0]);
if (windowHandles.length != 2) {
return false;
}
if (windowHandles[0].equals(parentWindowHandle)) {
driver.switchTo().window(windowHandles[1]);
} else {
driver.switchTo().window(windowHandles[0]);
}
return true;
}
});
Nope, Model window needs to be handle by javaScriptExecutor,Because majorly model window made up of window model,
This will works once model appeared then control take a place into model and click the expected element.
have to import javascriptexector
like below,
Javascriptexecutor js =(Javascriptexecutor).driver;
js.executescript(**<element to be clicked>**);
P.S. 1 adding my 2 cents even though the question is too old
public void PressEnterKey()
{
var simulator = new InputSimulator();
simulator.Keyboard.KeyPress(VirtualKeyCode.RETURN);
}
you can create a method like the above and call it where it is required.
P.S. 2 - you can change the keyboard inputs as well (like up arrow, down arrow, page down etc)