0

We have a test that is clicking a link, and going to the newly opened tab to check if it has gone to the right page. Is there a way to close this newly opened tab?

The step definitions currently look like this:

 /**
     * @Given /^the (?:|current )(?:url|page address|address|address of page) (?:should|does)(n\'t| not)? match "([^"]*)"$/
     */
    public
    function urlMatch($not, $compare)
    {
        $actual = $this->getSession()->getDriver()->getCurrentUrl();

        is_numeric(strpos($not, ' not')) || is_numeric(strpos($not, 'n\'t')) ? assertFalse(is_numeric(strpos($actual, $compare)), "Address is " . $compare) : assertTrue(is_numeric(strpos($actual, $compare)), "Address is " . $actual . ", not " . $compare);

    }

    /**
     * @Given /^(?:|.*)(?:A|a) new (?:window|tab)(?:|.*)$/
     */
    public
    function checkForNewWindow()
    {
        $windowNames = $this->getSession()->getWindowNames();
        if (count($windowNames) > 1) {
            return true;
        } else {
            throw new Exception("A new tab has not been opened");
        }
    }

    /**
     * @Given /^I switch to the new (?:window|tab)$/
     */
    public
    function switchToNewWindow()
    {
        $windowNames = $this->getSession()->getWindowNames();

        if (count($windowNames) > 1) {
            $this->getSession()->switchToWindow(end($windowNames));
        } else {
            throw new Exception("There is not a tab to switch to");
        }
    }

    /**
     * @Given /^I close the current (?:window|tab)(?:|.*)$/
     */
    public
    function closeCurrentWindow()
    {
        $window = $this->getSession()->getWindowName();
        $this->getSession()->stop($window);

    }

The final one of which does not work, as it simply stops the entire session.

Any suggestions?

KyleFairns
  • 2,947
  • 1
  • 15
  • 35
  • 1
    As far as I'm aware this has not been solved just yet, because it needs Javascript to be enabled. [Here](https://github.com/minkphp/Mink/issues/620) is the link to the open issue in Mink. – hasumedic Feb 24 '16 at 14:36
  • How about a way to send CMD + W to chromedriver? That might work, because that is the shortcut to close tabs on Mac OSX... – KyleFairns Mar 07 '16 at 14:13

1 Answers1

0

If you have a Mink session that supports executing JavaScript code you can close the current tab with the following step.

/**
 * @Given /^I close the current (?:window|tab)$/
 */
public function closeCurrentWindow()
{
    $this->getSession()->executeScript("window.open('','_self').close();");
}

For a discussion on what piece of JavaScript code works best in which browser, go there: How to close current tab in a browser window?

Marcel Pfeiffer
  • 1,018
  • 11
  • 12