Skip to content
CodeKruPro

Read values with JavaScript

Automation taskMediumAsked in: Infosys, TCS, Wipro

"When do you run JavaScript from a test?" One honest answer: to read something the WebDriver API does not expose directly. Here a script returns the page title and a field value. A value comes back only when the script uses return.

JavaScript Executor - Get Values

JavaScript Executor - Get Values

JavascriptExecutor lets you execute JavaScript directly in the browser. Cast the driver to execute JS:

JavascriptExecutor js = (JavascriptExecutor) driver;

A script only hands a value back to Java when it uses the return keyword; without it, executeScript() returns null.

Task:

  1. Navigate to https://testkru.com/Elements/TextFields
  2. Run a script with executeScript() that returns the page title from the document object
  3. Run a second script that finds the input with id preFilledTextField and returns its current value
  4. Print both values

Expected output:

JS Title: Text Fields
JS Value: Codekru