Effortlessly Handle Windows in Selenium with PHP

Himanshu Sheth

Posted On: April 12, 2021

view count90154 Views

Read time14 Min Read

One of the common scenarios in a web application (or a web app) is opening up a new browser window (or tab) once the user performs a specific activity. Many web developers use the HTML tag ‘__blank’ that informs the browser to open a new window (or tab, depending on the user’s set preference) when a link is clicked. Handling Windows in Selenium with PHP can be used for automating interactions with browser windows, tabs, and even pop-up windows.

Pop-up windows can ‘sometimes’ be annoying for the website visitors, but sometimes, you have no other choice than to use the same. How does Selenium differentiate between different windows or tabs? How can automation be used to switch between different browser windows or tabs seamlessly? How do you manage window handling in Selenium?

In this blog, we deep dive into Selenium usage for automating interactions with browsers, tabs, and pop-ups. We use the PHPUnit, the unit-testing framework for PHP, for demonstrating window handling in Selenium PHP. If you are preparing for an interview you can learn more through Selenium interview questions.

What is a Window Handle?

The Window Handle is a unique identifier whose primary responsibility is to hold all the windows’ address. When the Selenium WebDriver instance is instantiated, an alpha-numeric ID is assigned to the Window. The unique ID is called Window Handle, a pointer to the Window and helps identify the browser window.

Whether it is a new window/tab/pop-up, the Window Handle (or ID) is unique for each one of them. The Selenium WebDriver uses the Window Handle functions in Selenium PHP for switching between different windows (or tabs).

As far as the Window Handle’s retention is concerned, the unique ID is retained till the closure of the Selenium WebDriver session (i.e. either via WebDriver.Quit or WebDriver.Close APIs). The Window Handle functions are used for getting details of the handles of all the windows. The fundamentals of window handling in Selenium remain the same, irrespective of whether you are handling windows in Selenium with PHP or using Selenium with other programming languages (e.g. Python, Java, etc.).

Here are some of the common scenarios where you would encounter multiple windows (or tabs):

  • Forms that require selection of date from a newly opened window.
  • Button clicks that open a new tab (or Window).
  • Pop-ups which are used to show some offers to the end-user. Job portals commonly use this strategy.
  • Handling windows that show advertisements.

Shown above is a sample scenario where a click operation in the parent (or base) window opens up two ‘child windows’. Each of these has unique window handles, and the handle is retained till the windows are not destroyed (i.e. closed). With this, the total number of windows becomes three (parent + child-1 + child-2).

Click on a button/link in ‘Child-1’, and ‘Child-2’ opens ‘Grand Child-1’ and ‘Grand Child-2’ respectively. With this, the total number of windows are five, and each of them has unique Window handles that can be used to automate operations on them.

Commands for Handling Windows in Selenium with PHP

Selenium provides different methods for handling multiple windows. You can also refer to our guide to handle multiple windows with Selenium & Protractor. Here are some of the widely used commands in Selenium PHP testing for switching browser windows and handling pop-up windows:

If you are a PHP expert, you can acquire a benchmark industry certification specializing in core PHP programming skills and expand your opportunities to advance your career in PHP automation testing.

selenium php

SwitchTo Window

The SwitchTo command is used for switching the focus to a new browser window or tab. For changing the focus to a new window, the Window Handle of the desired browser window is passed as an argument to the command.

getWindowHandle

The getWindowHandle method in Selenium PHP returns the Window ID (which is a unique alpha-numeric identifier for the window) of the currently active (or focused) window.

In the example shown above, $wHandle is the ID of the window obtained using the getWindowHandle method.

getWindowHandles

This is an important method for handling windows in Selenium with PHP. The getWindowHandles method returns a set of window (and tab) handles opened by the same driver instance, including the parent and child windows. For example, if a click operation on a button in the parent window opens up a new tab; the getWindowHandles method will return the handles of the parent window and child window (i.e. tab). The sizeof operator when applied on the set returned by getWindowHandles returns the size of the set i.e. 2 in this case.

On a similar line, if a web page opened in the parent window opens up 8 pop-up windows; the Handle Count obtained by applying sizeof operator on the set returned by getWindowHandles method is 9.

Each of the windows will have a unique Window Handle (or Identifier) for easy identification of the window.

How to Handle Multiple Browser Windows, Tabs, and Pop-ups in Selenium PHP?

We demonstrate the test scenarios for window handling in Selenium PHP using PHPUnit on LambdaTest’s cloud-based Selenium Grid. Cross browser testing using PHPUnit on a cloud-based Selenium Grid helps in testing across different combinations of browsers, platforms, and device emulators.

To get started, we create an account on LambdaTest and note the user-name & access-key available on the profile page. The tests are performed on (Chrome 85.0 + Windows 10) combination. The browser capabilities are generated using the LambdaTest capabilities generator.

Handle Multiple Browser Windows

For installing the PHPUnit framework, we create a composer.json file for the project:

Run the command composer require, press ‘Enter’ button twice to proceed with the installation of the PHPUnit framework. On completion, PHPUnit framework (version 9.3) is installed.

The file composer.lock contains information of the dependencies and the vendor folder has all the dependencies.

The file vendor\autoload.php will be used in the test code so that classes (and its methods) provided by those libraries can be used in the implementation. Now it’s time to demonstrate the various scenarios for handling Windows in Selenium With PHP.

You can also refer to the below video tutorial on how to handle Windows and Frames in selenium.

Multiple Browser Window Handling in Selenium PHP

For demonstrating multiple window handling in Selenium PHP, we use the following test scenario:

  1. Open https://www.lambdatest.com in the Chrome browser.
  2. Get the Window Handle of the currently focused window.
  3. Open https://www.lambdatest.com/blog in a new window using the HTML attribute __blank.
  4. Print the respective window handles.
  5. Switch to the window where the second URL is opened.
  6. Assert if the window title does not match with the expected title.
  7. Close the window under focus.
  8. Switch to the first window and assert if the window title does not match with the expected title.
  9. Close the browser window.

Implementation

Code Walkthrough

  1. As the Selenium Grid on LambdaTest is used for testing, the user-name and access key are stored in global variables. The same can be obtained by visiting the profile page on LambdaTest.
  2. The browser capabilities are generated using the LambdaTest Capabilities Generator.
  3. The combination of global variables holding the user-name and access-key is used to access the Selenium Grid on LambdaTest [@hub.lambdatest.com/wd/hub].
    The create method in the RemoteWebDriver class takes the first parameter are the Selenium Grid URL and second parameter is the browser capabilities.
  4. In the test method – test_SwitchToNewWindow, the test URL https://www.lambdatest.com is opened and the getWindowHandle method offered by Selenium WebDriver is used to get the Window Handle of the current window.
  5. The JavaScript method window.open is used for creating a new secondary browser window. The height and width window dimensions are also passed to the method.

    The executeScript method offered by JavaScriptExecutor in Selenium PHP is used for executing the newly formed JavaScript code in the context of the currently opened window.

  6. The getWindowHandles method returns an alphanumeric array containing the Window ID (or handle) of the currently open windows. The sizeof operator on the array returned by getWindowHandles returns the number of opened windows (i.e. in our case, it is 2).
  7. Assert if the total number of window handles is less than 2.
  8. The switchTo method of Selenium WebDriver is used for switching to the second window (i.e. one which was opened using the window.open method).
    Assert is raised if the Window title does not match with the expected title.
  9. The current window is closed using the Close() method.
  10. Now the window handle count will be one (since only the parent window is open). The switchTo method is used for switching to the parent window, the handle (i.e. $wHandle) of which is passed as a parameter to the method.

    Raise an assert if the window title does not match with the expected one.

  11. The quit method of Selenium WebDriver in PHP is invoked as a part of the tearDown.

Execution

The two browser windows are open with URL 1 & URL 2. The WindowHandle of the second browser window is used with the SwitchTo() command for switching the context to the second window (that is opened using window.open JS method).

A similar approach is used for switching the context to the parent window on the child window’s closure.

Here is the execution snapshot where the PHPUnit framework was triggered for running the tests:

I hope this gives you a fairly good idea of handling windows in Selenium with PHP. Next up, we learn about handling multiple browser tabs in Selenium PHP.

Free Testing

Handling Multiple Browser Tabs in Selenium with PHP

For demonstrating handling of multiple browser tabs in Selenium PHP, we use the following test scenario:

  1. Open http://automationpractice.com/index.php in the Chrome browser
  2. Locate the ‘Youtube link’ on the test page and click on the link
  3. Switch to the newly opened browser tab
  4. Assert if the window title does not match with the expected title
  5. Close the window under focus
  6. Switch to the first window and assert if the window title does not match with the expected title
  7. Close the browser window

Implementation

Code Walkthrough

A significant part of the implementation in this part of the Selenium PHP tutorial remains the same as that used in handling windows in Selenium with PHP.

  1. On opening the test URL (i.e. http://automationpractice.com/index.php), the getWindowHandles method of WebDriver is used for getting the handles of the opened browser window(s).
  2. The web element with hyperlink to the site’s YouTube channel is located at the end of the page. The window.scrollTo method in JavaScript is executed using the executeScript method offered by JavaScriptExecutor. This will navigate to the end of the page.
  3. For getting information about the required web element, we use the POM Builder extension in Chrome to get the locator information (i.e. XPath).
  4. The findElement method of WebDriverBy class is used for getting details about the web element [with XPath – //a[contains(.,’Youtube’)].

  5. The click method is invoked on the located web element.
  6. The getWindowHandles method returns an alpha-numeric array (or set) that contains window handles (or Window ID) of the currently opened browser windows (or tabs). In our case, the number of open windows is 2.

    Hence, sizeof operator when applied to the array (or set) returned by getWindowHandles returns 2.

  7. The switchTo method of Selenium WebDriver is used for switching to the second window (i.e. $HandleCount[1]). Assert is raised if the window title does not match with the expected title.
  8. The close method closes the window under focus (i.e. tab where YouTube channel is open).
  9. Switch to the parent window (i.e. $HandleCount[0]). Assert if the titles do not match.

Execution

Here are the Window Handles of the two browser windows that were instantiated during testing:

Shown below is the Selenium test automation execution snapshot:

lambdatest youtube

As seen in the execution snapshot, the Window Handles of the parent window and tab are unique. When the window and tab is open, the size of the window handles array is 2.

Now that we have seen the implementation and execution for handling windows in Selenium with PHP as well as multiple tabs, let us learn more about handling multiple browser pop-up windows.

Handling Multiple Browser Pop-up Windows in Selenium with PHP

For demonstrating handling of browser popups in Selenium PHP, we use the following test scenario:

  1. Open http://www.popuptest.com/popuptest1.html in the Chrome browser.
  2. Close all the pop-up windows in reverse chronological order.
  3. Check if the title of the parent window matches the expected title.

If the same test is performed on a local Selenium Grid, you have to ensure that pop-ups are enabled for Google Chrome. For enabling, pop-ups for Chrome on the local machine, go to chrome://settings/ 🡪 Privacy and security 🡪 Site Settings 🡪 Pop-ups and redirects. Disable Block option for http://www.popuptest.com:80

Selenium Grid

Code WalkThrough

  1. On instantiation of the Chrome browser on LambdaTest Grid, the browser opens the test URL and 6 pop-up windows (i.e. Pop-up 1, Pop-up 2, …. Pop-up 6). Hence, the total window count is 7.
  2. Since pop-ups are not blocked, the site loads six pop-up windows. The getWindowHandles method returns a set of IDs of the currently open windows.

    The sizeof operation when performed on the set returned by getWindowHandles should return 7 (i.e. one parent window + six pop-up windows).

    The first element (i.e. $HandleCount[0]) in the set is the Window Handle of the parent window and the same is saved in a temporary variable (i.e. $mainHandle)

  3. A for loop is executed on the set of Window Handles available in $HandleCount. At every iteration, the WindowHandle (i.e. $handle) is compared with the Window Handle of the primary window (i.e. $mainHandle).

    If the current window handle is that of a pop-up window, the switchTo method is used to switch to the pop-up window. Selenium WebDriver’s close method is used for closing the pop-up window(s). The pop-up windows will be closed in the order – popup6.html 🡪 popup5.html 🡪 popup4.html 🡪 popup3.html 🡪 popup2.html 🡪 popup1.html. The loop is exited when all pop-up windows are closed and only one window is active (i.e. parent window).

  4. The switchTo method is used for switching to the parent window with handle $mainHandle. Assert is raised if the window title does not match with the expected title.

Execution

The window handles of the pop-up windows are marked below:

Only the parent window is left on the closure of all the pop windows, eventually closed after the test has been executed.

As seen in the execution snapshot obtained by visiting the automation tab on the LambdaTest platform, we notice that the pop-up windows are opened and later closed in reverse chronological order.

Conclusion

Browser windows, including tabs and pop-up windows, are identified using Window Handles. These handles act as Window IDs and are unique for every browser window. In this Selenium WebDriver PHP tutorial, we had a look at handling windows in Selenium with PHP using methods like switchTo, getWindowHandle, and getWindowHandles. These methods are instrumental in window handling in Selenium test automation with PHP.

Happy Selenium Automation Testing ☺

Author Profile Author Profile Author Profile

Author’s Profile

Himanshu Sheth

Himanshu Sheth is a seasoned technologist and blogger with more than 15+ years of diverse working experience. He currently works as the 'Lead Developer Evangelist' and 'Senior Manager [Technical Content Marketing]' at LambdaTest. He is very active with the startup community in Bengaluru (and down South) and loves interacting with passionate founders on his personal blog (which he has been maintaining since last 15+ years).

Blogs: 128



linkedintwitter

Test Your Web Or Mobile Apps On 3000+ Browsers

Signup for free