Switch to window
Window selectors
Before starting to automate a desktop or web application (bot clicking, typing, etc), you need to switch to a particular window by its unique parameters:
- Handle
- Title
- Name
- Class
- Instance
note
You can search windows by exact match or by a regular expression (REGEXPNAME, REGEXPTITLE, etc.).
Web browser windows
The following window properties can be used to switch to a particular browser window (tab) using Web driver (Chrome, IE, Firefox, Edge):
Text string
Title: see how to switch to browser window by its title:
window('Confluence - Chrome')Handle: the window handle value is dynamic so you need to get it for each bot execution using
driver().getWindowHandle()ordriver().getWindowHandles()methods. See how to switch to browser window by its handle:window('CDwindow-(EC7514DEC6898198C75C31A50145CAE7)')
Desktop windows
The following window properties can be used to switch to a particular desktop app window using Desktop driver:
Text string
Title: see how to switch to desktop app window by its title:
window('Open file')Handle: see how to switch to desktop app window by its handle:
window('[HANDLE:0x0000000000020340]')
CSS: see how to switch to desktop app window by its title, class, name, instance in CSS notation:
window('.window-class[title^=Submit]') window('*[class$=Total Commander]') window('[name*=Submit]') window('.window-class[instance=4]')Object
NAME, REGEXPNAME
window('[NAME: New Connection]') window('[REGEXPNAME: .Connection]')CLASS, REGEXPCLASS
window('[CLASS: V8Win]') window('[REGEXPCLASS: V.]')TITLE, REGEXPTITLE
window('[TITLE: V8Win]') window('[REGEXPTITLE: V.]')INSTANCE
window('[INSTANCE: 3]')
Switching to windows and browser tabs
Some web applications have many frames or multiple windows. The Web Driver assigns an alphanumeric ID to each window as soon as the WebDriver object is instantiated. This unique alphanumeric ID is called window handle . RPA driver uses this unique ID to switch control among several windows. In simple terms, each unique window has a unique ID, so that robot can differentiate when it is switching controls from one window to the other.
getWindowHandle
Purpose: to get the window handle of the current window.
Return a string of alphanumeric window handle:
Set<String> handle = driver().getWindowHandle();
// output for chrome: CDwindow-(EC7514DEC6898198C75C31A50145CAE7)
getWindowHandles
Purpose: to get the window handle of all the current windows.
Return a set of window handles:
Set<String> allHandles = driver().getWindowHandles();
// output for desktop driver: [[HANDLE:0x0000000000010768], [HANDLE:0x0000000000020340], [HANDLE:0x00000000000C075C], [HANDLE:0x0000000000040758], [HANDLE:0x00000000000107B0], [HANDLE:0x0000000000010406]]
switchTo Window
Purpose: WebDriver supports moving between named windows using the switchTo method.
switchTo().window("windowName");
Alternatively, you can pass a window handle to the switchTo().window() method. Knowing this, it’s possible to iterate over every open window like so:
// be careful with the SEARCH_ALL_WINDOWS capability as driver will close all windows when the script finishes execution!
for (String handle : driver().getWindowHandles()) {
switchTo().window(handle);
}
You can also switch between windows with Iterators:
import com.workfusion.odf2.compiler.BotTask;
import com.workfusion.odf2.core.task.AdHocTask;
import com.workfusion.odf2.core.task.TaskInput;
import com.workfusion.odf2.core.task.output.TaskRunnerOutput;
import com.workfusion.odf2.core.webharvest.rpa.RpaDriver;
import com.workfusion.odf2.core.webharvest.rpa.RpaFactory;
import com.workfusion.odf2.core.webharvest.rpa.RpaRunner;
import com.workfusion.rpa.driver.Driver;
import com.workfusion.rpa.helpers.RPA;
import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebElement;
import org.slf4j.Logger;
import javax.inject.Inject;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;
@BotTask(requireRpa = true)
public class SwitchToWindows implements AdHocTask {
private final RpaRunner rpaRunner;
private final Logger logger;
@Inject
public SwitchToWindows(RpaFactory rpaFactory, Logger logger){
this.rpaRunner = rpaFactory
.builder(RpaDriver.UNIVERSAL)
.closeOnCompletion(true)
.build();
this.logger = logger;
}
@Override
public TaskRunnerOutput run(TaskInput taskInput) {
rpaRunner.execute(driver->{
this.switchWindowWithIterator(driver);
});
return taskInput.asResult()
.withColumn("example_bot_task_output", "completed_successfully");
}
private void switchWindowWithIterator(Driver driver){
RPA.openChrome("https://www.w3schools.com/tags/att_a_target.asp");
RPA.$(".w3-btn.w3-margin-bottom").click();
RPA.sleep(2000);
Set<String> windowHandles = driver.getWindowHandles();
logger.debug("Number of window handles " + windowHandles.size());
String firstWindowHandle = driver.getWindowHandle();
logger.debug(firstWindowHandle + "First window handle");
windowHandles.remove(firstWindowHandle);
String winHandle = windowHandles.iterator().next();
if(!winHandle.equals(firstWindowHandle)){
String secondWindowHandle = winHandle;
RPA.switchTo().window(secondWindowHandle);
RPA.sleep(100);
RPA.switchTo().frame("iframeResult");
RPA.sleep(1000);
String header = driver.findElement(By.xpath("/html/body/h1")).getText();
logger.debug("Second Window IFRAME Content - " + header);
//Switch to chrome driver if want's to show chrome pop up because currently it is using universal driver
driver.switchDriver("chrome");
RPA.switchTo().defaultContent();
driver.executeScript("alert(\"Second Window Content -> \" + arguments[0])",header);
RPA.sleep(3000);
RPA.switchTo().alert().accept();
}
}
private void popAlert(Driver driver,String popupMessage){
driver.switchDriver("chrome");
//Switch to default content inorder to work with alert if already on a IFrame
RPA.switchTo().defaultContent();
String script = popupMessage;
driver.executeScript("alert(arguments[0])",script);
RPA.sleep(3000);
RPA.switchTo().alert().accept();
}
}
switchToExistingWindow Command
Purpose: WebDriver supports switching to existing window (already opened).
With default timeout 100 milliseconds:
<robotics-flow>
<robot driver="desktop" name="desktopDriver" close-on-completion="true">
<capability name="SEARCH_ALL_WINDOWS" value="true"/>
<script><![CDATA[
switchToExistingWindow("[REGEXPTITLE:(.*)new (\\d+) - Notepad++]");
]]>
</script>
</robot>
</robotics-flow>
With custom timeout specified in milliseconds:
<robotics-flow>
<robot driver="desktop" name="desktopDriver" close-on-completion="true">
<capability name="SEARCH_ALL_WINDOWS" value="true"/>
<script><![CDATA[
switchToExistingWindow("[REGEXPTITLE:(.*)new (\\d+) - Notepad++]", 10000);
]]>
</script>
</robot>
</robotics-flow>
With custom timeout specified in milliseconds (without Simplified API):
<robotics-flow>
<robot driver="desktop" name="desktopDriver" close-on-completion="true">
<capability name="SEARCH_ALL_WINDOWS" value="true"/>
<script><![CDATA[
driver().switchTo().window("[REGEXPTITLE:(.*)new (\\d+) - Notepad++]", 10000);
]]>
</script>
</robot>
</robotics-flow>
Switching to frames and popups
Purpose: WebDriver supports moving between named frames using the switchTo method.
switchTo().frame("frameName or id")
tip
See more information about iframes in Handling iFrames.
switchTo PopUp Command
Purpose: WebDriver supports moving between named popUps using the switchTo method. After you’ve triggered an action that opens a popup, you can access the alert and it will return the currently open alert object. With this object you can now accept, dismiss, read its contents or even type into a prompt. This interface works equally well on alerts, confirms, and prompts.
alert = switchTo().alert()
tip
See more information about alerts in Handling JavaScript alerts.
Other switch commands
- switchToLastWindow() – switching focus to the last opened window
- switchToNextWindow() – switching focus to the next opened window after current window
- switchToPrevWindow() – switching focus to the previously opened window before current window
- switchToRootWindow() – switching focus to the first opened window
Examples
The example below shows how to manipulate window handles and switch between browser windows.
Expand to see how to switch to windows by their handle
import com.workfusion.odf2.compiler.BotTask;
import com.workfusion.odf2.core.task.AdHocTask;
import com.workfusion.odf2.core.task.TaskInput;
import com.workfusion.odf2.core.task.output.TaskRunnerOutput;
import com.workfusion.odf2.core.webharvest.rpa.RpaDriver;
import com.workfusion.odf2.core.webharvest.rpa.RpaFactory;
import com.workfusion.odf2.core.webharvest.rpa.RpaRunner;
import com.workfusion.rpa.driver.Driver;
import com.workfusion.rpa.helpers.RPA;
import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebElement;
import org.slf4j.Logger;
import javax.inject.Inject;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;
@BotTask(requireRpa = true)
public class SwitchToWindows implements AdHocTask {
private final RpaRunner rpaRunner;
private final Logger logger;
@Inject
public SwitchToWindows(RpaFactory rpaFactory, Logger logger){
this.rpaRunner = rpaFactory
.builder(RpaDriver.UNIVERSAL)
.closeOnCompletion(true)
.build();
this.logger = logger;
}
@Override
public TaskRunnerOutput run(TaskInput taskInput) {
rpaRunner.execute(driver->{
this.switchingWindowUsingHandle(driver);
});
return taskInput.asResult()
.withColumn("example_bot_task_output", "completed_successfully");
}
private void switchingWindowUsingHandle(Driver driver){
RPA.timeouts().implicitlyWait(10, TimeUnit.SECONDS);
RPA.openChrome("https://rpa-tutorial.s3.amazonaws.com/trainings/new-window.html");
RPA.sleep(2000);
String firstWindowHandle = driver.getWindowHandle();
logger.debug("=================" + firstWindowHandle);
WebElement newBrowerTabButton = driver.findElement(By.xpath("//button[contains(text(),'New Browser Tab')]"));
newBrowerTabButton.click();
RPA.sleep(2000);
Set<String> windowHandles = driver.getWindowHandles();
driver.switchDriver("chrome");
RPA.switchTo().window(firstWindowHandle);
RPA.switchTo().defaultContent();
this.popAlert(driver,"About to switch between different browser tabs");
for(String handle : windowHandles){
logger.debug("=================" + handle);
RPA.switchTo().window(handle);
RPA.sleep(2000);
}
}
private void popAlert(Driver driver,String popupMessage){
driver.switchDriver("chrome");
//Switch to default content inorder to work with alert if already on a IFrame
RPA.switchTo().defaultContent();
String script = popupMessage;
driver.executeScript("alert(arguments[0])",script);
RPA.sleep(3000);
RPA.switchTo().alert().accept();
}
}
note
There is no cross browser solution for manipulating with tabs, so we show the example solution for Chrome.
Expand to see how to open a new tab using CTRL + click
import com.workfusion.odf2.compiler.BotTask;
import com.workfusion.odf2.core.task.AdHocTask;
import com.workfusion.odf2.core.task.TaskInput;
import com.workfusion.odf2.core.task.output.TaskRunnerOutput;
import com.workfusion.odf2.core.webharvest.rpa.RpaDriver;
import com.workfusion.odf2.core.webharvest.rpa.RpaFactory;
import com.workfusion.odf2.core.webharvest.rpa.RpaRunner;
import com.workfusion.rpa.driver.Driver;
import com.workfusion.rpa.helpers.RPA;
import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebElement;
import org.slf4j.Logger;
import javax.inject.Inject;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;
@BotTask(requireRpa = true)
public class SwitchToWindows implements AdHocTask {
private final RpaRunner rpaRunner;
private final Logger logger;
@Inject
public SwitchToWindows(RpaFactory rpaFactory, Logger logger){
this.rpaRunner = rpaFactory
.builder(RpaDriver.UNIVERSAL)
.closeOnCompletion(true)
.build();
this.logger = logger;
}
@Override
public TaskRunnerOutput run(TaskInput taskInput) {
rpaRunner.execute(driver->{
this.openNewBrowserTabUsingCTRLClick(driver);
});
return taskInput.asResult()
.withColumn("example_bot_task_output", "completed_successfully");
}
private void openNewBrowserTabUsingCTRLClick(Driver driver){
RPA.timeouts().implicitlyWait(10, TimeUnit.SECONDS);
RPA.openChrome("https://wikipedia.org");
this.popAlert(driver,"Switching to Wiki News");
WebElement wikinewsSpan = driver.findElement(By.xpath("//span[contains(text(),'Wikinews')]"));
RPA.actions().moveToElement(wikinewsSpan)
.keyDown(Keys.CONTROL)
.click(wikinewsSpan)
.keyUp(Keys.CONTROL)
.perform();
RPA.sleep(2000);
Set<String> tabs = driver.getWindowHandles();
List<String> tabss = new ArrayList<>(tabs);
this.popAlert(driver,"Bot will switch to 2nd Tab now");
RPA.switchTo().window(tabss.get(1));
this.popAlert(driver,"Opening Google Finance");
RPA.openChrome("https://finance.google.com");
RPA.sleep(2000);
this.popAlert(driver,"Closing Google Finance and switching to first tab");
RPA.close();
RPA.switchTo().window(tabss.get(0));
this.popAlert(driver,"Opening stackoverflow.com ");
RPA.openChrome("https://stackoverflow.com/");
}
private void popAlert(Driver driver,String popupMessage){
driver.switchDriver("chrome");
//Switch to default content inorder to work with alert if already on a IFrame
RPA.switchTo().defaultContent();
String script = popupMessage;
driver.executeScript("alert(arguments[0])",script);
RPA.sleep(3000);
RPA.switchTo().alert().accept();
}
}