Establish a connection to the current active session using Selenium JavaScript WebDriver

When I'm using Node.js along with the selenium-webdriver package for running my tests, a new session is started and a new window opens each time a test begins. I've been attempting to retrieve the session Id and make use of it later by calling getSession() (reference link )

var webdriver = require('selenium-webdriver');
var SeleniumServer = require('selenium-webdriver/remote').SeleniumServer;

var server = new SeleniumServer('./seleniumServer/selenium-server-standalone-2.43.1.jar', {
    port: 4444
});
server.start();

var driver = new webdriver.Builder()
        .usingServer(server.address())
        .withCapabilities(webdriver.Capabilities.firefox())
        .build();

console.log(driver.getSession());

However, this is resulting in an exception being thrown:

getSession();
^
TypeError: Object [object Object] has no method 'getSession'
    at Object.<anonymous> (\testing\demo_1.js:14:3)
    at Module._compile (module.js:456:26)
    at Object.Module._extensions..js (module.js:474:10)
    at Module.load (module.js:356:32)
    at Function.Module._load (module.js:312:12)
    at Function.Module.runMain (module.js:497:10)
    at startup (node.js:119:16)
    at node.js:906:3

Could someone please help me identify what's causing the issue and guide me on how to obtain and set the selenium session id?
Furthermore, I am eager to learn how to utilize the sessionId for connecting to an existing browser session.

Answer №1

Credit goes to gm2008 for pointing me in the right direction with their insightful response. I encountered an issue where the attachToSession function was appearing as undefined, possibly due to an update in implementation (I am utilizing version 4.0.0-alpha.1 of selenium-webdriver). Nonetheless, I managed to achieve the desired functionality using the TypeScript code below:

import wd, { WebDriver, Session } from 'selenium-webdriver'
import { HttpClient, Executor } from 'selenium-webdriver/http'

// The server URL is obtained from running selenium-standalone on my local machine
const server: string = 'http://localhost:4444/wd/hub'

async function createNewBrowserSessionId(): Promise<string> {
  const browser: WebDriver = new wd.Builder()
    .withCapabilities(wd.Capabilities.chrome())
    .usingServer(server)
    .build()

  const session: Session = await browser.getSession()

  return session.getId()
}

async function accessExistingBrowser(sessionId: string): Promise<WebDriver> {
  const client: HttpClient = new HttpClient(server)
  const executor: Executor = new Executor(client)
  const session: Session = new Session(sessionId, wd.Capabilities.chrome())

  return new WebDriver(session, executor)
}

async function executeOperationsOnBrowser(browser: WebDriver): Promise<void> {
  await browser.get('https://www.google.com/')
}

async function shutdownBrowser(browser: WebDriver): Promise<void> {
  await browser.close()
}

async function establishConnectionAndPerformTasks(): Promise<void> {
  const sessionId: string = await createNewBrowserSessionId()
  const existingBrowser: WebDriver = await accessExistingBrowser(sessionId)

  await executeOperationsOnBrowser(existingBrowser)
  await shutdownBrowser(existingBrowser)
}

establishConnectionAndPerformTasks()

If you maintain the session open and have a method of sharing the ID, you can connect to the existing Session even after the script that initializes it has finished executing. The shutdownBrowser() function can be utilized when you are prepared to perform cleanup.

Answer №2

If you have successfully built your webdriver, the driver object should now include a method called getSession(). The documentation for getSession() can be found here.

However, it's important to note that what is returned by getSession() is actually a promise. This means that you won't receive the session id directly from the return value. To get the session id, you need to do the following:

 driver.getSession()
                .then( function(session){
                    var session_id = session.getId();
                });

Chances are, you will need to save the session id in a file. Then, when running the program again, you can attach to this session id using the following function:

browser = webdriver.WebDriver.attachToSession(...);

The documentation for the above function can be found here.

However, one issue with the attachToSession() call is that it doesn't provide feedback on whether it was successful. As a workaround, I suggest calling browser.getTitle() using the returned WebDriver object and waiting for it to resolve or reject. This way, you'll know if you've successfully attached to the session id.


Setting up the webdriver:

In response to user3789620's question, here is the code snippet for setting up the webdriver:

var webdriver_server = 'http://localhost:9515', // chromedriver.exe serves at this port 
chrome = require('selenium-webdriver/chrome'),
options = new chrome.Options(),
webdriver = require('selenium-webdriver'),
Http = require('selenium-webdriver/http');
options.setChromeBinaryPath(your_chrome_binary_path);

var browser = new webdriver.Builder()
  .withCapabilities(webdriver.Capabilities.chrome())
  .setChromeOptions(options)
  .usingServer(webdriver_server)
  .build()

if (typeof saved_session_id !== 'undefined' && saved_session_id !== "") {
  console.log("Going to attach to existing session of id: " + saved_session_id);
  client = new Http.HttpClient(webdriver_server);
  executor = new Http.Executor(client);
  browser = webdriver.WebDriver.attachToSession(executor, saved_session_id);
}

Answer №3

If you want to keep your sessions active, consider using cookies for persistence. The webdriver.WebDriver.Options documentation can provide guidance on this. One method is to store the cookies in an external file before ending the session, then loading them from that file each time you start a new test.

Answer №4

If you encounter issues, consider utilizing attachToSession() in this manner:

webdriver.attachToSession(sessionId);

For additional information, refer to the documentation.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How can you prevent the 'Script not responding' error when using Reverse AJAX / Comet?

My worker thread is responsible for sending requests to the server using XMLHttpRequest. The request is directed to a php file which checks the integrity of client information. If the client requires new data, it is sent. Otherwise, the server continuously ...

Rendering in ThreeJS Causes IE11 to Crash

I encountered a peculiar issue with Internet Explorer 11 while working on WebGL programming. Everything was functioning smoothly in all browsers until, out of the blue, IE started crashing when altering the positions of 4 meshes, without pointing to any sp ...

Creating a JavaScript function to download specific sections of an HTML page

Currently, I am implementing PHP MySQL in my HTML page. I have already utilized several div elements in my page. I successfully created a print button that prints a specific div on the page. Now, I am looking to add a download button that will allow users ...

Image uploading using AJAX onchange event

Is it possible to use AJAX to upload images when using the input onchange event? I've attempted various methods but none of them seem to be working. Here is the code I am currently using: $(document).ready(function (e) { $("#uploadForm").on(&apos ...

Troubleshooting a JQuery AJAX Autocomplete problem involving PHP and MySQL

I am facing an issue with my autocomplete feature. It is functioning properly on one of my pages, but not on this particular page. Even though the correct number of entries is being retrieved, they all appear to be "blank" or are displayed in black text th ...

The controller failed to return a value when utilizing the factory

I am attempting to pass a value from my view to the controller using a function within the ng-click directive. I want to then use this value to send it to my factory, which will retrieve data from a REST API link. However, the value I am sending is not ret ...

Revise if a specific file is not being called by AJAX

I am currently utilizing a routing library known as Grapnel.js. It requires URLs in the format of index.php#something/something, which is why I am using htaccess to rewrite /something/something to match that structure. However, I would like the flexibility ...

Creating static HTML files for non-static pages using Next.js SSR/ISR

While troubleshooting an issue with a specific page, I noticed that a static HTML file was created for a non-static page using Next.js. Is this expected? The page, which we will refer to as "page1," does not include the functions getStaticPaths() or getSta ...

Is there a way to trigger a function upon the loading of a template in Angular 2?

I'm a newcomer to angular2 and I need to trigger a function when a template loads or initializes. I have experience with achieving this in angular1.x, but I'm struggling to figure out how to do it in angular-2. Here's how I approached it in ...

Looking for giphy link within a v-for loop (Vue.js)

I am fetching a list of movie characters from my backend using axios and rendering them in Bootstrap cards. My objective is to search for the character's name on Giphy and use the obtained URL as the image source for each card. However, when I attemp ...

The WYSIWYG niceEdit editor is incompatible with textareas generated through ajax-php calls, causing it to malfunction

My AJAX-generated textarea is not converting into a WYSIWYG Editor once loaded. The normal textarea works fine, but I need assistance in solving this issue. <!DOCTYPE html> <html> <head> ........ $.ajax({ type: "POST", ...

Navigate pages in Python Selenium without directly relying on the current URL

Is there a way to loop through multiple pages without relying on driver.current_url in Selenium? When I try to navigate through the pages using a loop, I encounter errors. However, if I don't use it, the code runs fine but only goes through one page. ...

Guide to updating 2 iframes simultaneously with a single link/button using HTML and JavaScript

Just joined the community and looking for help on how to refresh two different iframes within a single page. I came across a solution on Google that involves using getElementById. However, I've heard Firefox can be tricky with IDs. Appreciate any as ...

The new mui v5 Dialog is having trouble accepting custom styled widths

I am facing an issue with my MUI v5 dialog where I cannot seem to set its width using the style() component. import { Dialog, DialogContent, DialogTitle, Paper, Typography, } from "@mui/material"; import { Close } from "@mui/icons- ...

"Patience is key when it comes to waiting for components to render

Short Overview of the Issue I'm currently exploring methods to access an onRendered lifecycle hook. Finding on the Topic A similar query was posted here: Vue $nextTick in mounted() hook doesn't work as expected The explanation provided suggests ...

When utilizing React, I generated an HTML page with a distinct .js file, however, encountered two unexpected errors

Update : Gratitude to everyone who has helped me in tackling this issue. One user suggested using a web server, but my intention was to find a solution using just a single HTML and JS file. Even though I tried following the steps from a similar question o ...

Updating the rotation of a grandchild in Three.js Object3D

In my current project, I am attempting to make the grandchild of a rotated Object3D element face towards the camera using the lookAt() method. I have experimented with various approaches to achieve this. However, the source code for the Object3D.lookAt() ...

Discovering the audio file URL hidden within javascript code

Is it possible to programmatically locate a link to an audio pronunciation clip on a website? I am in the process of creating a personalized language learning Anki deck. The specific site I am referring to is: When clicking on "Framburður," the audio cli ...

What methods can be used to modify element attributes in Python?

I'm curious about how to utilize Python to modify an element in the HTML code of a webpage: In this case, I need to change it from: <input _ngcontent-mcp-c552="" type="number" name="bpm" placeholder="0" min= ...

Is it possible to enlarge pixel art in EaselJS without causing blurriness?

As I develop a game using EaselJS with pixel art that I'm enlarging, I've encountered an issue. Whenever I scale the art, the image becomes blurry. Is there a method to have it drawn using nearest neighbor filtering? ...