webdriver | webdriver test | selenium executor | Search

The code imports necessary classes and functions from the selenium-webdriver module and defines a function closeAllWindows that closes all browser windows except the one specified by the keep argument. The function creates a new instance of WebDriver, gets an array of window handles, and iterates over them to close all windows except the one specified by keep.

Run example

npm run import -- "close all windows"

close all windows

const { WebDriver, Capabilities, Session } = require('selenium-webdriver')
const createExecutor = importer.import("selenium executor")

const LOCAL_URL = 'http://localhost:4444/wd/hub';

async function closeAllWindows(driver, sessionId, keep) {
  let driver2 = new WebDriver(
    new Session(sessionId, Capabilities.chrome()), createExecutor(Promise.resolve(LOCAL_URL)))

  try {
    let windows = await driver2.getAllWindowHandles()
    console.log('closing session ' + sessionId[1] + ' windows ' + windows)
    for(let i = 0; i < windows.length; i++) {
      if(windows[i] != keep) {
        await driver2.switchTo().window(windows[i])
        await driver2.close()
      }
    }
  } catch (e) {
    console.log(e)
  }
}

module.exports = closeAllWindows

What the code could have been:

const { Builder, Capabilities, until } = require('selenium-webdriver');
const createExecutor = require('selenium-executor').default;

const LOCAL_URL = 'http://localhost:4444/wd/hub';

/**
 * Closes all browser windows except the one specified by `keep`.
 * 
 * @param {WebDriver} driver - The WebDriver instance
 * @param {string} sessionId - The session ID of the WebDriver instance
 * @param {string} keep - The handle of the window to keep open
 */
async function closeAllWindows(driver, sessionId, keep) {
  // Create a new WebDriver instance with the specified session ID and capabilities
  const driver2 = await new Builder()
   .usingServer(LOCAL_URL)
   .withCapabilities(Capabilities.chrome())
   .build();

  try {
    // Get all window handles
    const windows = await driver2.getAllWindowHandles();

    console.log(`Closing session ${sessionId.slice(1)} windows ${windows}`);

    // Iterate over all window handles and close the ones that are not 'keep'
    for (let i = 0; i < windows.length; i++) {
      if (windows[i]!== keep) {
        // Switch to the current window and close it
        await driver2.switchTo().window(windows[i]);
        await driver2.close();
      }
    }
  } catch (e) {
    console.error(e);
  } finally {
    // Ensure the driver is closed after use
    await driver2.quit();
  }
}

module.exports = closeAllWindows;

Code Breakdown

Imports

const { WebDriver, Capabilities, Session } = require('selenium-webdriver')
const createExecutor = importer.import('selenium executor')

Constants

const LOCAL_URL = 'http://localhost:4444/wd/hub';

Function

async function closeAllWindows(driver, sessionId, keep) {
  //...
}

Function Body

let driver2 = new WebDriver(
  new Session(sessionId, Capabilities.chrome()), createExecutor(Promise.resolve(LOCAL_URL)))

//...
try {
  let windows = await driver2.getAllWindowHandles()
  console.log('closing session'+ sessionId[1] +'windows'+ windows)
  for(let i = 0; i < windows.length; i++) {
    if(windows[i]!= keep) {
      await driver2.switchTo().window(windows[i])
      await driver2.close()
    }
  }
} catch (e) {
  console.log(e)
}

Export

module.exports = closeAllWindows