Obey Rush84
Obey Rush84

Reputation: 1

Ignore driver.close when there is no newly opened windows

I'd like to use driver.close() on a newly opened windows but in this case i'm not sure if a pop up windows is gonna open up every time I click on an element so the idea is to tell selenium to ignore driver.close if there is no newly opened windows. Thanks.

Upvotes: 0

Views: 149

Answers (1)

Ben
Ben

Reputation: 1371

You didn't mention which language you were using so here how it's done in Javascript (it will be easy to translate to another language using the Selenium documentation):

const handles = await driver.getAllWindowHandles();
if (handles.length > 1) await driver.switch_to.window(handles[-1]).close();

Note that the previous code snippet assumes that it is always the last opened window that should be closed and that there is only one window to close.

It could be a mistake in some cases, so here is a safer way to close all tabs/windows which are not the active one:

const handles = await driver.getAllWindowHandles();
if (handles.length > 1) {
  const currentHandle = await driver.getWindowHandle();
  handles
    .filter((handle) => handle !== currentHandle)
    .map(async (handle) => {
      await driver.switchTo().window(handle);
      await driver.close();
    });
  // don't forget to switch back to the original window
  await driver.switchTo().window(currentHandle);
}

Upvotes: 1

Related Questions