Is there a way to physically close a tab via Protractor or WebDriver?
I ask because while I know how to switch tabs programmatically, but it does not bring the active tab to the foreground. I can't always tell what is going on in my E2E tests that run on SauceLabs because when I view the screen casts it is showing the tab that I navigated away from, not the active one.
Am I going about this incorrectly?
it('should do something in the previous tab', function(done) {
browser.getAllWindowHandles().then(function (handles) {
browser.switchTo().window(handles[0]);
// do something
expect(something).toEqual(thisThing);
done();
});
});
C# Version of Sakshi's answer:
You can use
driver.close
and then switch to active tabdriver.SwitchTo().Window(m_driver.WindowHandles.First());
or any another available tabClose all tabs except first one and switch to first tab:
Pay attention to last two lines, they are need to avoid such errors like
OpenQA.Selenium.NoSuchWindowException: no such window: target window already closed from unknown error: web view not found
First of all, selenium does not provide a reliable cross-browser API to work with browser tabs. A common approach to open or close a tab (although not quite reliable) is to invoke browser shortcuts for Chrome:
CTRL
/COMMAND
+T
CTRL
/COMMAND
+W
In protractor, find the
body
element and "send keys" to it:Or, using
browser.actions()
:Also, to open a new tab, there is an interesting hack (introduced here), which basically injects a new
a
element into the page and invokesclick
mouse event:There is also
window.close()
function, but it would not close the tab if it was not opened viawindow.open()
(reference). In other words, if this is a tab you manually open, then you can usewindow.open() -> window.close()
approach with the help ofbrowser.executeScript()
.I am using the command below to close the current tab after opening the link in new tab
Then, you can switch to the last tab by issue the command:
You can try the following:
Switch to the new opened tab. Close the current windows (in this case, the new tab). Switch back to the first window.