orchestration | tile selenium chrome windows | send a joke | Search

This code uses Selenium to manage multiple browser sessions, resizing and retrieving URLs from each window across all active sessions. It is designed for use in a testing environment and can be executed asynchronously.

Run example

npm run import -- "get all session and window urls"

get all session and window urls

var importer = require('../Core');
var resizeWindow = importer.import("resize selenium window");

var windowCounter = -1;
function repositionSession(client, s, reposition = true) {
    client.sessionId = s.id;
    return client
        .getUrl()
        .then(() => client.getWindowHandles())
        .then(h => {
            return importer.runAllPromises(h.map(hwnd => resolve => {
                windowCounter++
                return client
                    .switchToWindow(hwnd)
                    .then(() => reposition ? resizeWindow(client, windowCounter) : [])
                    .then(() => client.getUrl())
                    .catch(e => console.log(e))
                    .then(r => resolve(r))
            }));
        });
}

function getAllSessionUrls(client, reposition = true) {
    var session, urls;
    session = client.sessionId;
    return client
        .getSessions()
        .then(r => {
            return importer.runAllPromises(r.map(s => resolve => {
                return repositionSession(client, s, reposition)
                    .catch(e => e.message.includes('chrome not reachable') ? [] : console.log(e))
                    .then(r => resolve(r));
            }));
        })
        .then(r => {
            client.sessionId = session;
            urls = r;
        })
        .catch(e => console.log(e))
        .then(() => urls)
}

module.exports = getAllSessionUrls;

if(typeof $ !== 'undefined') {
    $.async();
    getAllSessionUrls(false)
        .then(r => $.sendResult(r))
        .catch(e => $.sendError(e))
}

What the code could have been:

const { importer } = require('../Core');
const { resizeWindow } = importer.import('resize selenium window');

/**
 * Repositions a session by switching to it, resizing the window, and returning the current URL.
 * @param {object} client - The selenium client.
 * @param {object} s - The session object.
 * @param {boolean} [reposition=true] - Whether to reposition the session or not.
 * @returns {Promise<string>} A promise resolving to the current URL of the session.
 */
async function repositionSession(client, s, reposition = true) {
  try {
    client.sessionId = s.id;
    const urls = await Promise.all([
      client.getUrl(),
      client.getWindowHandles().then(h => h.map(hwnd => {
        return client.switchToWindow(hwnd).then(() => {
          if (reposition) {
            resizeWindow(client, client.getWindowHandles().indexOf(hwnd));
          }
          return client.getUrl();
        });
      })),
    ]);
    return urls[1];
  } catch (e) {
    if (e.message.includes('chrome not reachable')) {
      return '';
    } else {
      throw e;
    }
  }
}

/**
 * Retrieves URLs of all sessions and optionally repositions them.
 * @param {object} client - The selenium client.
 * @param {boolean} [reposition=true] - Whether to reposition the sessions or not.
 * @returns {Promise<string[]>} A promise resolving to an array of URLs.
 */
async function getAllSessionUrls(client, reposition = true) {
  try {
    const sessions = await client.getSessions();
    const urls = await Promise.all(sessions.map(async s => {
      try {
        return await repositionSession(client, s, reposition);
      } catch (e) {
        // Ignore errors
        return '';
      }
    }));
    return urls;
  } catch (e) {
    throw e;
  }
}

module.exports = getAllSessionUrls;

if (typeof $.$!== 'undefined') {
  $.$async();
  getAllSessionUrls(false)
   .then(r => $.sendResult(r))
   .catch(e => $.sendError(e));
}

This code manages and repositions multiple browser sessions, allowing you to retrieve URLs from each session.

Here's a breakdown:

  1. Imports:

  2. repositionSession(client, s, reposition = true):

getAllSessionUrls(client, reposition = true)

Module Exports

Async Execution (if $ is defined)

Summary

This code snippet is designed to manage and interact with multiple browser windows within a Selenium testing environment. It allows you to:

The code is structured to be reusable and adaptable to different testing scenarios.