javascriptjavaseleniumselenium-webdriver

result of jsExecuteScript is null in Java while result in browser console is a String value


https://www.companyfolders.com/proofs

when I'm running a script in the browser's console on the above page:

document.querySelector('.subscribe_form input').value

I see the placeholder value as a result of running: "Enter your email address"

but when I'm trying to do this in Java: I'm navigating to this page then trying to execute:

JavascriptExecutor js = (JavascriptExecutor)driver;
String emailPlaceholder = String.valueOf(js.executeScript("document.querySelector('.subscribe_form input').value"));

I always see 'null' as a result of execution or NullPointerException if I'm using .toString() or casting to (String)

NullPointerException

any ideas what I'm doing wrong? or why this script doesn't work in Java selenium?


Solution

  • put a return in the javascript statement

    js.executeScript("return document.querySelector('.subscribe_form input').value")
                      ^^^^^^
    

    https://www.selenium.dev/selenium/docs/api/java/org/openqa/selenium/JavascriptExecutor.html

    Some background explanation:

    The browser console is developed for humans. To that end the browser will try to print a sensible representation of a return value for the human. Even if you did not explicitly typed return. Because that is what you most likely wanted to see when you type javascript statements in the browser console.

    The selenium js executor does not follow that design philosophy. Instead you have to do an explicit return.