Before we go any further, let’s understand why and when the switch method is used for. Frames, notifications, and windows can be switched using Selenium Switch Methods. Before performing an action inside the frame, alert, or window, our Test Script needs to switch. If we don’t switch, an exception is raised by the application. switchTo() provides access to the different Selenium switch methods. In order to transmit a future command, switchTo() returns a target location.
Switch To Frame
There are 4 ways to choose a frame and only one way to go to the parent context:
webElement.element.frame(frame) – chooses a frame from a webelement.
frame(String nameOrId) – chooses a frame by name or ID with the function frame(String nameOrId).
frame(int index) – By using its (zero-based) index, frame(int index) chooses a frame.
defaultContent() – The main document or the first frame is chosen by defaultContent().
parentFrame() – Change the focus to the parent context with parentFrame().
It will either be a frame or an iframe element if an application has a frame. Even though there are differences, we typically refer to both parts as frames. Despite this, the majority of applications include an iframe or inline frame. It’s intended to support the application’s continued interactivity.
Switch To Alert
A pop-up box is an alert notifying the user or requesting a certain action. There are 3 different sorts of notifications and 4 different things you may do with an alert. The 3 different alert kinds are:
Information Alert: Contains 1 button and a message.
Confirmation Alert: This alert has a message and two buttons.
Prompt Alert: The prompt alert message has two buttons and a text entry box.
What should be done in response to the alert is:
accept() acknowledges the alert.
Dismiss() function cancels the alert.
The getText() method retrieves the alert’s text.
The sendKeys() function enters text into the alert.
An alarm is typically displayed with a grey disabled backdrop. The website is grey because it cannot be used to perform an action. The alarm needs to be handled in some way.
The test script that follows switches to the alert and accepts it if the pop-up image was an alert.
@Test
public void demoSwitchToAlert () {
driver.get(“https://blog.perficient.com/”);
driver.switchTo().alert().accept();
}
Switch To Window
All windows have a distinct alphanumeric id that Selenium assigns. The id is used to switch control between each window and is referred to as a window handle. There are two techniques for obtaining the window handle:
Get the current window handle with getWindowHandle().
Get a list of window handles with getWindowHandles().
The following statement lines get the window handle and window handles:
String mainHandle = driver.getWindowHandle(): gets the HomePage window handle.
Set <String> allHandles = driver.getWindowHandles(): gets both window handles.
Happy Testing!
Leave A Comment