Behat Switch between multiple Windows

Profile picture for user devraj

While automating any website, we must have witnessed a scenario where multiple windows open within an application when a button or link is clicked and the user has to perform some action on all the opened windows. User might not be able to work on all windows at the same time and hence need some way through which he can take control over multiple windows.

Consider an example of automationpractice.com, when in footer if you will click on any of social media icon say Facebook, it will open a new window for you. Assume we want to switch between the windows and print the url.

Here is my scenario:

  @frame
  Scenario: Work with multiple frames
    Given I am on homepage
    When I click on facebook icon
    Then I switch to windows

This is my corresponding steps for The I switch to windows

/**
   * @Then /^I switch to windows$/
   */
public function iSwitchToParentWindows()
{
    $windowNames = $this->getSession()->getWindowNames();

    if(count($windowNames) > 1)
    {
        $this->getSession()->switchToWindow($windowNames[1]);
        print($this->getSession()->getCurrentUrl());
    }
}

This will output url of facebook page like https://www.facebook.com/groups/525066904174158/

Here, we are storing all the windowNames in variable $windowNames array. And if size or count of array is greater than 1 we are switching to facebook window with index 1 using switchWindow method and window name. Then we are printing current url of the page.

In case you will use index 0, it will print the url of parent window:

$this->getSession()->switchToWindow($windowNames[0]);

This statement is same as:

$this->getSession()->switchToWindow();

because if you will specify null in argument it will switch back to parent window.

Behat invalid argument: "handle must be a string" Error while switching Windows

Now, if you are getting below error

invalid argument: 'handle' must be a string
(Session info: chrome=89.0.4389.114)
Build info: version: '3.141.59', revision: 'e82be7d358', time: '2018-11-14T08:25:53'
System info: host: 'Taruns-MBP.lan', ip: 'fe80:0:0:0:18c8:22fc:838c:6ea3%en0', os.name: 'Mac OS X', os.arch: 'x86_64', os.version: '10.16', java.version: '12.0.2'
Driver info: driver.version: unknown (Exception)

Then you need to set w3c: false in your behat.yml, example:

capabilities:
    extra_capabilities:
        chromeOptions:
            args:
                - "--start-fullscreen"
            w3c: false

After chrome version 75 or 76, you might be getting this error, setting w3c capability to false is one of the way to handle it.

Tags