Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

protractor switch to previous tab

After opening a new tab (second) I'm trying to switch to the first tab.

     common.clickOpenNewSession(); //it opens the new tab

 browser.getAllWindowHandles().then(function (handles) {
    var secondWindowHandle = handles[1];
    var firstWindowHandle = handles[0];
    browser.switchTo().window(secondWindowHandle).then(function () { //the focus moves on new tab
        browser.sleep(3000);
        expect(browser.driver.getCurrentUrl()).toContain("url");
//do some actions

    });
//below it doesn't work. I try to go back on previous tab without closing the second tab
    browser.actions().sendKeys(protractor.Key.CONTROL).sendKeys(protractor.Key.TAB).perform();
    browser.sleep(4000);
    browser.driver.switchTo().window(firstWindowHandle);
    browser.setLocation('http://google.com');
});
like image 361
Ana Avatar asked Nov 07 '14 09:11

Ana


Video Answer


2 Answers

The problem is that you're trying to go to the previous tab by using ctrl + tab, instead of using the window handles to switch back. This is not supported in WebDriver, because using ctrl + tab is a system operation, and can't be emulated on your browser for all OS/browsers. Just use browser.switchTo() again.

like image 60
Jmr Avatar answered Oct 09 '22 13:10

Jmr


@Aaron This code get all the browser handles available and resolves the promise. Then opens the tab created by a <a href='newlink' target='_blank'>Link</a>:

POFile.buttonWithABlankTarget.click().then(function() {
    browser.getAllWindowHandles().then(function(handles) {
        var newTabHandle = handles[1];
        browser.switchTo().window(newTabHandle).then(function () {
            // Expect the newly opened tab URL to equal the href of the invitation
            expect(browser.driver.getCurrentUrl()).toContain("http://...");
        });
    });
});

In the same fashion, you could switch between tabs:

it("should open the first tab", function() {
    browser.getAllWindowHandles().then(function (handles) {
        browser.switchTo().window(handles[0]);
    });
});

And, of course, close a tab:

it("should close the second tab and return to the first tab", function() {
    browser.getAllWindowHandles().then(function (handles) {
        // We currently are on the second tab...
        browser.driver.close();
        browser.switchTo().window(handles[0]);
    });
});

Hope this helps!

like image 27
Tim Visser Avatar answered Oct 09 '22 12:10

Tim Visser