Switch Commands

 

We often find situations where we might have to switch our focus/webdriver control to another window, popup, message box or frame. The reason we might have to do this is because of the way WebDriver has been designed. In short suffice to say that there is almost a separate DOM associated with each of the types mentioned above. And since Selenium WebDriver has been designed to handle only one DOM at a time with the reference handle we create, we will have to switch the references to be able to do operations. Lets see some examples below.

Switch to a new Window (using title)

Here we are switching to a window whose title is known to us.

 Switch to a new Window (using windows handle)

Here we are switching to the last window that was opened

Switch to javascript alert pop up

Here we are switching to a pop up and clicking ‘ok’ on the pop up

Switch to frame(or iframe)

Here we are switching to an iframe using its ‘name’ attribute. Subsequently we are retrieving the ‘body’ tag inside the frame and printing its text to see that we indeed were able to switch to an iframe

 

Just as a revision, here are the steps to take every time you would want to run the cucumber scenarios that are part of this tutorial:

1) You have completed the Setup and First Script section (all sub links)

2) Create a file “Switches.feature” by right-clicking ‘features’ folder. Copy the gherkin code under the section “Complete Cucumber Scenario”

3) Either individually create step_definitions by following the videos that are at the bottom of Setup and First Script sections pages OR if you are lazy, just right click features\step_definitions folder and create a file “Switches.rb” and copy the code under “Step Definitions” section below.

 

Complete Cucumber Scenario

Step Definitions