Is there a way to close a tab in WebDriver or Protractor? Is there a way to close a tab in WebDriver or Protractor? selenium selenium

Is there a way to close a tab in WebDriver or Protractor?


You can try the following:

  1. Switch to the new opened tab.
  2. Close the current windows (in this case, the new tab).
  3. Switch back to the first window.

    browser.getAllWindowHandles().then(function (handles) {browser.driver.switchTo().window(handles[1]);browser.driver.close();browser.driver.switchTo().window(handles[0]);});


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:

  • open tab: CTRL/COMMAND + T
  • close tab: CTRL/COMMAND + W

In protractor, find the body element and "send keys" to it:

var body = element(by.tagName("body"));body.sendKeys(protractor.Key.chord(protractor.Key.CONTROL, "t"))body.sendKeys(protractor.Key.chord(protractor.Key.CONTROL, "w"))

Or, using browser.actions():

browser.actions().keyDown(protractor.Key.CONTROL).sendKeys('t').perform();browser.actions().keyDown(protractor.Key.CONTROL).sendKeys('w').perform();

Also, to open a new tab, there is an interesting hack (introduced here), which basically injects a new a element into the page and invokes click mouse event:

function openNewTab (url) {    return browser.driver.executeScript(function(url) {(        function(a, url){            document.body.appendChild(a);            a.setAttribute('href', url);            a.dispatchEvent((function(e){                e.initMouseEvent("click", true, true, window, 0, 0, 0, 0, 0, true, false, false, false, 0, null);                return e;            }(document.createEvent('MouseEvents'))))        }(document.createElement('a'), url)    );    }, url)};

There is also window.close() function, but it would not close the tab if it was not opened via window.open() (reference). In other words, if this is a tab you manually open, then you can use window.open() -> window.close() approach with the help of browser.executeScript().


C# Version of Sakshi's answer:

   var tabs = driver.WindowHandles;   if (tabs.Count > 1)   {       driver.SwitchTo().Window(tabs[1]);       driver.Close();       driver.SwitchTo().Window(tabs[0]);   }