Tips for addressing the Stale Element Reference Exception when locating an element in JMeter

Trying to locate an element with a structure similar to the following:

<div>
 <div>
  <div>
    <ul>
     <object id = "obj"
       #document (link here)
        <html>
         <head> </head>
          <body>
            <div id = style4 >

I have attempted various methods to find this element, but it consistently results in a stale element exception. Here's what I've tried:

 var table = wait.until(pkg.ExpectedConditions.presenceOfElementLocated(pkg.By.xpath('/html/body/div[8]/div/div/div[2]/div/div[2]/div/div/ul')));
    WDS.browser.executeScript("arguments[0].scrollIntoView(true);", table);
    WDS.log.info("Got Table");

    // Find the <object> element within the table
    var objectElement = table.findElement(pkg.By.tagName('object'));
    WDS.log.info("Found objectElement");

    // Extract the content of the <object> element
    var objectContent = objectElement.getAttribute('data');
    WDS.log.info("Extracted objectContent");

    // Refresh the <object> element to prevent staleness
    WDS.browser.executeScript("arguments[0].scrollIntoView(true);", objectElement);
    WDS.log.info("Refreshed objectElement");

    // Load the content document of the <object> element
    var contentDocument = WDS.browser.executeScript("return arguments[0].contentDocument", objectElement);
    WDS.log.info("Loaded contentDocument");

    // Find the <html> element within the content document
    var htmlElement = contentDocument.querySelector('html');
    WDS.log.info("Found htmlElement: " + htmlElement);

This is the accompanying log:

2024-02-21 22:42:12,278 INFO c.g.j.p.w.s.WebDriverSampler: Got Table
2024-02-21 22:42:12,289 INFO c.g.j.p.w.s.WebDriverSampler: Found objectElement
2024-02-21 22:42:12,304 INFO c.g.j.p.w.s.WebDriverSampler: Extracted objectContent
2024-02-21 22:42:12,309 INFO c.g.j.p.w.s.WebDriverSampler: Refreshed objectElement
2024-02-21 22:42:12,317 ERROR c.g.j.p.w.s.WebDriverSampler: Error: org.openqa.selenium.StaleElementReferenceException: stale element reference: stale element not found
  (Session info: chrome=122.0.6261.58)

Answer №1

You may have inadvertently created the issue yourself by utilizing the JavascriptExecutor. It is unlikely that a real user would go through the trouble of opening the browser developer tools, accessing the console, and entering

var table = document.getElementById....)
.

To avoid StaleElementReference errors, use an Explicit Wait for any element operation, such as replacing this:

var element = WDS.browser.findElement(pkg.By.id('foo'))
//something else
element.click()

You can instead do:

wait.until(pkg.ExpectedConditions.presenceOfElementLocated(pkg.By.id('foo'))).click()

When it comes to using JavaScript, it might not be the most optimal choice. In general, it's recommended to utilize JSR223 Test Elements and the Groovy language for scripting due to Groovy offering superior performance. Additionally, Nashorn engine has been removed in JDK 15, meaning JavaScript will no longer be supported in future Java versions.

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

Is it possible for a memory leak to occur when a jQuery object is created within a function but never actually used?

As an illustration: function calculateTime(minutes) { var newTime = new Date(); newTime.setHours(0, minutes, 0, 0); return angular.element('<input type="hidden"/>').timepicker('setTime', newTime).val(); } I'm cu ...

Tips for developing an npm package that includes a demonstration application

When creating packages, I believe it's important to include a demo app. However, I'm unsure about the best way to organize the file structure for this purpose. My goal is to have one Github repository containing both my published NPM module and ...

Retrieving Data from Web using Python Selenium

I've been trying to extract information from a website (snippet provided below) The process involves entering data, moving to another page for more inputs, and eventually displaying a table. However, I'm encountering an issue at this stage: dri ...

Is it necessary for TypeScript classes that are intended for use by other classes to be explicitly exported and imported?

Is it necessary to explicitly export and import all classes intended for use by other classes? After upgrading my project from Angular 8 to Angular 10, I encountered errors that were not present before. These issues may be attributed to poor design or a m ...

Confirming the presence of an image using jQuery without enforcing it as mandatory

Situation: In my setup, I maintain a database that holds details about various items. Currently, I utilize a dynamic form to retrieve and exhibit the existing information on any item stored in the database. Any modifications made on the form are promptly ...

Transform JavaScript code to integrate with a pre-existing WebSocket within a React.js application

I have created a JavaScript code to establish connections with my own Ruby WebSocket server, where it waits for incoming messages, parses them, and then displays content based on certain conditions (the implementation details are not relevant at the moment ...

The Jquery calculation is giving unexpected results by returning NaN instead of an integer

Hello, I'm attempting to create a calculation that will add up the values from multiple text inputs and then display the total in another text input field. Below is the code that I have put together for this purpose. However, when I test it out, I see ...

Creating duplicates of a parent mesh in THREE.js with its children and additional materials

I am inquiring about a cloning issue I am having with a mesh that has a parent and 4 children, each with different materials. When I clone the parent mesh using this code: let result = cloudObjects.sideCloudGeometry[texture].clone(); The cloned mesh look ...

In the JavaScript example provided, do child classes inherit their parent class prototype?

Here's the code I'm working with: class Rectangle { constructor(w, h) { this.w = w; this.h = h; } } Rectangle.prototype.area = function () { return (this.w * this.h); }; class Square extends Rectangle { construct ...

Connect external script actions to HTML elements within components

I'm attempting to incorporate an external script Within public/index.html <script src="https://embed.selly.gg"></script> An event should trigger when I click on a button with specific data attributes. Inside components/shop/ShopItem.js ...

Tips for altering objects within an array

I am dealing with an array of objects that looks like this: const items = [ {name: 'Sam', amount: '455gbjsdbf394545', role: 'admin'}, {name: 'Jane', amount: 'iwhru84252nkjnsf', role: 'user'}, ...

Utilizing Selenium JavaScript to insert a cookie into a request

Trying to add a cookie to the request in Selenium using JavaScript. I followed the documentation at this link, but my code snippet doesn't seem to pass any cookies to the PHP script below on the server. Here is the client-side JavaScript code: var w ...

retrieve object from s3 using angular and open it as a pdf

I'm attempting to access a file from an s3 bucket using Angular and display it as a PDF. I have a node service set up to retrieve the object, which I then call from Angular. However, when I try to open the PDF in Angular, it appears as a blank (white) ...

Is it feasible for JSON.stringify to maintain functions in its serialization?

Consider this item: x = { "key1": "xxx", "key2": function(){return this.key1} } Suppose I execute the following code: y = JSON.parse( JSON.stringify(x) ); After running the above code, y will contain { "key1": "xxx" }. Is there a way to include funct ...

Once the GeoJson data is loaded with map.data.loadGeoJson, the circle events are obscured by the polygons from the

When I use map.data.loadGeoJson() to load a Geo Json file, the markers and circles on my map are being covered by polygons and their events cannot be clicked. Below are some sample codes for reference. How can this issue be resolved? Is there another way ...

Showing navigation items in Vuejs based on authentication status

In my current project, I am developing a Single Page Application (SPA) using vuejs with vuetify and integrating authentication via a laravel/passport API. The challenge I'm facing is related to conditional rendering of navigation icons based on user a ...

When a menu item is clicked, apply a class and change the display property to

I currently have an HTML menu with a submenu structured as follows: <li id="item-3" class="menu-item has-children-3"> <a href="#" class="sf-with-ul"><span>Auto</span></a ...

Showing the computation outcome on the identical page

I have implemented a table within my PHP code. In the second column of this table, it typically displays "---". However, once I click the submit button, the same page should now display the calculated result. Here is an example: <table> <tr>& ...

What is the best way to ensure Selenium Python clicks on the right button?

I have just started exploring Selenium and am currently working on a web scraping project. I want to automate the process of clicking on the "16. token URI" button, inputting a number into the designated field, and then clicking on the Query button on a ...

Preserve the height of the previous div following an AJAX request

I am currently facing an issue where I have a script that utilizes ajax to receive a response containing a cart string (html code) with items from the cart. Inside the response handler, there is another script that sets the height of each div in the cart s ...