Home > Mobile >  Getting error org.openqa.selenium.JavascriptException: javascript error: Cannot read properties of n
Getting error org.openqa.selenium.JavascriptException: javascript error: Cannot read properties of n

Time:01-31

I am automating a web page (using Selenium with Java) where I have to click on a button on the webpage. After clicking the button, a new window opens up and I am able to switch to the new window using Window handles. However, the new window consists of a data table, whose all entries are hidden in the form:

<tr >
    <td >
        <input type="hidden" name="createdBy[0]" value="TESTOR02"> 
        TESTOR02 
        <br> 
        <input type="hidden" name="createdTimestamp[0]" value="JAN 30, 2023"> 
        JAN 30, 2023 
    </td>
    <td valign="top" >
        <input type="hidden" name="text[0]" value="Test Agreement Text Six"> 
        Test Agreement Text Six 
    </td>
</tr>

Now, when I am searching this value in console using >> document.querySelector("tr:nth-child(2) > td:nth-child(2) > input[type=hidden]").value, I am getting the correct output. However, when I am running this through automation script >>

JavascriptExecutor js = (JavascriptExecutor) driver;
String text = (String) js.executeScript("document.querySelector('tbody > tr.tdtable_even_row > td:nth-child(2) > input').value");
System.out.println(text);

I am getting the error >> org.openqa.selenium.JavascriptException: javascript error: Cannot read properties of null (reading 'value')

Any inputs as to why automation is giving the error but browser console is giving correct output and how to fix this?

I tried to get the desire output through automation as is displayed in browser console, however error is being displayed in automation script

CodePudding user response:

Can you try this on your code

String text = (String) js.executeScript("return document.querySelector('tr.tdtable_even_row td:nth-child(2) input[type=hidden]').value");

CodePudding user response:

The error is occurring because the element you are trying to access is not found on the page. The selector you are using in the automation script, document.querySelector('tbody > tr.tdtable_even_row > td:nth-child(2) > input'), is not finding the desired hidden input element.

To fix this, you can try using a more specific selector to target the desired element, for example:

String text = (String) js.executeScript("return document.querySelector('input[name=\'text[0]\']').value");
System.out.println(text);

You can also try waiting for the element to be present on the page before accessing it, using WebDriverWait:

WebDriverWait wait = new WebDriverWait(driver, 10);
WebElement element = wait.until(ExpectedConditions.presenceOfElementLocated(By.cssSelector("input[name='text[0]']")));
String text = (String) js.executeScript("return arguments[0].value", element);
System.out.println(text);
  • Related