Having trouble setting a value with sendKeys in Firefox using C# Selenium, and JavaExecutor isn't solving the issue

Hello everyone,

I'm facing a bit of a challenge here that I've been struggling with for some time now. I'm trying to create an automation strategy for a Trading Platform (specifically Trading212) using C# and Selenium.

Everything was going smoothly until I encountered the overlay for Placing an order. I attempted to use sendKeys as usual, but it didn't work out well:

Issues

-Error ElementNotInteractableException (Can't be scrolled into view)
-Error ElementNotInteractableException (Element is not reachable by keyboard)
-js.ExecuteScript("arguments[0].value='12345';", TargetPriceInput); (Changes a value just not the value)

The problem lies with the Price field, which seems impossible to modify. It has a dynamically changing ID, making it challenging to select. I could only identify it by looking for an input with "Text".

Element in Question:

    <div class="spinner _focusable" tabindex="-1" data-dojo-attach-event="onkeydown: onKeyDown" id="uniqName_0_131" widgetid="uniqName_0_131">
        <span class="spinner-placeholder" data-dojo-attach-point="placeholderNode">Price</span>
        <input type="text" autocomplete="off" id="uniqName_0_132" widgetid="uniqName_0_132">
        <div class="spinner-arrow-container">
            <div class="spinner-arrow spinner-down svg-icon-holder" data-dojo-attach-point="spnLeftNode"><svg class="svg-icon dropdown-arrow-down-icon" width="32" height="32" viewBox="0 0 32 32">
        <g fill="none" fill-rule="evenodd">
            <polyline stroke="#6F6F7F" points="20.5 14.5 16 19 11.5 14.5" stroke-linecap="round"></polyline>
        </g>
    </svg>
    </div>
            <div class="spinner-arrow spinner-up svg-icon-holder" data-dojo-attach-point="spnRightNode"><svg class="svg-icon dropdown-arrow-up-icon" width="32" height="32" viewBox="0 0 32 32">
      <g fill="none" fill-rule="evenodd">
        <polyline stroke="#6F6F7F" points="20.5 18.5 16 14 11.5 18.5" stroke-linecap="round"></polyline>
      </g>
    </svg></div>
        </div>
        <div class="spinner-disabled-click-catcher" data-dojo-attach-point="clickCatcherNode"></div>
    </div>

It appears that JavaScript controls the updates when a key is pressed while the box is selected. However, I couldn't figure out how to make Selenium select the box or input data into it. There are events attached to the input box, but I can't find a way to proceed.

                    TargetPrice.Click();
                    TargetPrice.SendKeys("05485.00000");

Both attempts resulted in errors and did not work as expected. Here is the original appearance of the panel

Upon inspecting with Firefox Inspector, I discovered that the hidden value of the Element is like a string: "1.31407". Despite being able to update it using ExecuteScript, the validation fails. The value updates visibly, but upon clicking elsewhere, it reverts back.

Further investigation revealed that there might be JavaScript scripts manually evaluating my keypresses and interfering. I'm unsure how to overcome this obstacle.

Event OnKeyDown

function, o = i.checkIntegerPartLength, s = i.onKeyPressed, l = this.state, d = l.currentValue, u = l.maxInputLength, h = this.getPrecision(), f = !1;
for (var p in r.default)
  if (void 0 === v[p] && r.default[p] === t.keyCode) {
    f = !0;
    break
  }(t.altKey || 18 === t.keyCode) && (t.stopPropagation(), t.preventDefault());
var g = String.fromCharCode(t.keyCode);
!f && isNaN(parseInt(g, 10)) && 190 != t.keyCode && 110 != t.keyCode && 109 != t.keyCode && 189 != t.keyCode && (t.stopPropagation(), t.preventDefault()), 190 != t.keyCode && 110 != t.keyCode || 0 != h && -1 === this.domNode.value.indexOf(".") || (t.stopPropagation(), t.preventDefault()), 189 != t.keyCode && 109 != t.keyCode || (this.onMinusPress(), t.stopPropagation(), t.preventDefault()), t.shiftKey && !isNaN(parseInt(g, 10)) && (t.stopPropagation(), t.preventDefault());
var m = (g = t.keyCode || t.charCode) == r.default.HOME || g == r.default.END || g == r.default.DELETE || g == r.default.BACKSPACE || g >= 37 && g <= 40;
if (!m && !o && c.default.getLength(this.domNode.value.replace(/\s/g, "")) >= u + h && this.domNode.selectionStart == this.domNode.selectionEnd && t.preventDefault(), !(a || t.keyCode !== r.default.NUMPAD_0 && f)) {
  var C = this.domNode.value.split("."),
    y = n(C, 1)[0],
    b = 48 == t.keyCode || 96 == t.keyCode,
    w = this._getTextSelection(this.domNode),
    T = w.start,
    L = w.length,
    _ = this.domNode.value.length === L;
  0 === T && "." !== this.domNode.value.charAt(L) && !_ && y.length && b && t.preventDefault()
}
if (o && !m && 190 !== t.keyCode && 110 !== t.keyCode) {
  var N = this.domNode.value.split("."),
    S = n(N, 2),
    E = S[0],
    I = S[1],
    x = this.domNode.value.indexOf("."),
    M = this._getTextSelection(this.domNode),
    O = M.start,
    P = M.length,
    A = E.substr(O, P),
    D = A && (A.length > 1 || 160 !== A.charCodeAt(0));
  E.replace(/\s/g, "").length >= u && !D && (!I && -1 === x || O <= x) && t.preventDefault()
}
"0" != d || h || m || 48 != t.keyCode && 96 != t.keyCode || t.preventDefault(), 65 == g && t.ctrlKey && this.domNode.select(), setTimeout((function() {
  e._destroyed || (s(), e.updateState(e.domNode.value, {
    isUserTyping: !0,
    keepCursorPosition: !0
  }))
}), 5)
}, onFocusEvent: function() {
    var t = this.props,
      e = t.o

I'm willing to provide any additional information needed. The trading212 demo webpage I'm working on is publicly accessible if you have any insights on how to tackle this issue.

I've already attempted virtual keystrokes using a separate library, but even Windows-based methods don't seem to work strangely.

EDIT: After extensive examination and retesting, utilizing the XPath system suggested in the answer below, I discovered that the reason none of my previous attempts made sense was because I was modifying the wrong element, similar to the correct one. To temporarily resolve this, I used Firefox inspection, selected the target input field, right-clicked, and copied -> XPath.

This provided me with a direct path to the correct XPath.

IWebElement XPathInput = driver.FindElement(By.XPath("/html/body/div[7]/div[2]/div[3]/div[2]/div[1]/div[3]/div/div[2]/div/input"));

Answer №1

UPDATE: Consider using XPATH in the following way:

IWebElement XPathSpan = driver.FindElement(By.XPath("descendant::span[@class='spinner-placeholder' and text()='Price']")); //confirm it has located the span element
IWebElement XPathInput = driver.FindElement(By.XPath("following-sibling::input")); //this should represent your input field

Your current XPATH is suitable, but if the DOM structure changes with an additional div, it may cause issues. The critical aspect here is that descendant instructs the search to go down through the descendants of the selected element. As you are utilizing driver.FindElement(), it starts its search at the root of the document. In the second line, we begin from the span and direct it to locate the first sibling input element, which should be the one you need.

My suggestion would be to locate it using XPATH: "descendant::span[text() = 'PRICE']/following-sibling::input"

This method appears more reliable in case another input element is added or similar changes occur.

If the parent element has the class "spinner _focusable" and some JavaScript functionality for onkeydown, I recommend finding and interacting with that element first before dealing with the price input.

Here are the steps to follow:

  1. Locate the input field using the XPATH provided above
  2. Find the parent element of the input, for example, var inputParent = input.FindElement(By.XPath("parent::div")) //assuming 'input' is the variable name from step 1
  3. Perform a click action on inputParent
  4. Use Thread.Sleep(500); or a WebDriverWait to wait for JavaScript to execute
  5. Input data into the input field

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 does a browser automatically fill in email and password fields?

When using a text input and a password input in my single page app, Chrome often prompts to remember the information for autofill. However, I am encountering an issue where it doesn't actually autofill the information. Does anyone know how to trouble ...

Obtaining Data from an XML Node Using AJAX

Trying to extract statistics from my XML based on a specific name request, but encountering issues with my JavaScript functionality. XML data: <player> <forward><name>Joe</name><stats>45</stats></forward> <f ...

Emscripten WebAssembly: Issue with Exporting Class "Import #13 module="GOT.func" error: the module does not exist as an object or function"

Exploring the potential of WebAssembly in a project as an importable function module, I decided to dive into using C++ with Emscripten. Implementing functions was smooth sailing, but running into obstacles when it comes to classes. My goal is to expose and ...

A situation occurred with Selenium where the element's reference became outdated during an explicit wait

When writing my Selenium test code, I encountered issues with element reference exceptions. The specific lines causing problems are: Clicking a check box Selecting an item from a drop-down menu Submitting a form by clicking a button Below is the snippet ...

Compiling TypeScript files with an incorrect path when importing, appending "index" at the end of the @angular/material library

I'm currently working on creating a library to collect and distribute a series of Angular components across various projects, with a dependency on angular/material2. My objective is to eventually publish it on npm. However, I've encountered an i ...

Unresolved error causing promise to throw an exception

My code is causing an error when resolve is called: Possibly unhandled Error: undefined at Promise$_rejecter (c:\projects\Test\promiseftp\node_modules\bluebird\js\main\promise.js:602:58) at WriteStream.<a ...

Ways to include a CSS file path in a link tag from an npm package

I have recently installed a package using npm. npm install lightgallery Now, I am trying to fill the href attribute of a link with the css file directory of this package. Here is what I have so far: <link rel="stylesheet" href="/node_mod ...

Erroneous deletion issue in React list causing removal of incorrect item

While working on creating a todo list in React, I faced an issue when trying to implement a delete function. The problem arose when attempting to delete an item - instead of removing the selected item, React ended up deleting everything except that specif ...

Issue with displaying partial view via Ajax request

I have managed to display a partial view using jQuery.ajax in my code: Html <div id="product-pop-up" style="display: none; width: 700px;"> <div class="product-page product-pop-up"> <div class="row" id="modalBody"> & ...

Utilizing JavaScript variables imported from an external library in Next.js: A Guide

I am currently working on a Next.js with Typescript website and I am in the process of adding advertisements. The ad provider has given me instructions to embed this JavaScript code on my site: <script src="//m.servedby-buysellads.com/monetization. ...

Posting an array using jQuery's AJAX feature

Consider the following JavaScript array structure: testarr = new Array(); testarr[0] = new Array(); testarr[0]["#FFFFFF"] = "White"; testarr[0]["#FFFFFF"] = new Array(); testarr[0]["#FFFFFF"]["#FFFFFA"] = "A"; testarr[0]["#FFFFFF"]["#FFFFFB"] = "B"; test ...

Is it necessary to use explicit wait (ExpectedConditions) for every web element in Selenium Webdriver Java with TestNG & POM?

Currently, the web application code for my project is developed by a third party and there is uncertainty about whether ajax or other technologies are being used to load web elements at different times. Our testing approach involves automating the web appl ...

Streamline Opera Mini Testing with Appium and Selenium

While exploring methods to test mobile web apps using Appium and the mobile SDK, I came across automation techniques for Opera browser tests. One can utilize Selenium or Appium along with Opera Chrome or Presto drivers (imported libraries) to achieve this. ...

The t.replace function is not available in Selenium RC

Currently, I am using Selenium 2.25 with Firefox 3.6 and encountering issues when running my scripts. The error displayed in my console and system is an alert message saying "Type error $j undefined" ERROR: Command execution failure. For error details fr ...

Tips for invoking a function in an ASP.NET code-behind file using JavaScript

I'm currently trying to display an image in my div by calling a function from the code behind file. The image tag is dynamically bound with JavaScript, but I'm having trouble figuring out how to call a function with parameters. The code snippet I ...

What steps can I take to prevent the "onclick" event from triggering multiple times?

I'm struggling to create a button that, when clicked, reveals a message input area. I am using the "onclick" attribute in the HTML and I want to ensure that the button is only clickable once to avoid generating multiple textareas on subsequent clicks. ...

Tips on cycling through hovered elements in a specific class periodically

I'm looking to add a hover animation to certain elements after a specific time, but I haven't been able to make it work correctly. Here's my attempted solution: CODE $(document).ready(function(){ function setHover() { $(' ...

What is the proper way to handle a 504 response header in an AJAX request using jQuery?

Recently, I encountered an issue with an AJAX call from the client that caught my attention. Here is a snapshot of how it looked: $.ajax({ 'url': '/converter/ajax-make-corrections/', 'data': { ...

Instructions for adding and removing a class when a Bootstrap modal is scrolled past 300 pixels

Having trouble getting the scroll to top function to work on a specific div. I'm using window.scroll function but it's not functioning correctly. Can someone please assist? $(window).scroll(function() { var scroll = $(window).scrollTop ...

49.0 version of Firefox coupled with Selenium 2.9.1

When attempting testing with Selenium 2 and phpunit, I encounter an issue. I am utilizing selenium-server-standalone-2.53.1.jar, but when I launch the test, Firefox opens blank and does nothing. The error message displayed by phpunit is as follows: PHPU ...