Skip to main content
Version: 10.3.2

Execute JavaScript

JavaScript is the preferred language inside the browser to interact with an HTML document object model (DOM). It means that a Browser has a JavaScript implementation in it and understands the JavaScript commands. You can disable it using browser options in your browser. The web driver still uses JavaScript to perform some actions.

For example, the XPath element search is implemented in JavaScript for Internet Explorer for you to overcome the lack of an XPath engine in this browser.

executeJavaScript(script, arguments)

JavaScriptExecutor comes separately and also comes under the WebDriver, but both do the same thing.

import com.workfusion.odf2.compiler.BotTask;
import com.workfusion.odf2.core.task.AdHocTask;
import com.workfusion.odf2.core.task.TaskInput;
import com.workfusion.odf2.core.task.output.TaskRunnerOutput;
import com.workfusion.odf2.core.webharvest.rpa.RpaDriver;
import com.workfusion.odf2.core.webharvest.rpa.RpaFactory;
import com.workfusion.odf2.core.webharvest.rpa.RpaRunner;
import com.workfusion.rpa.driver.Driver;
import com.workfusion.rpa.helpers.RPA;
import com.workfusion.rpa.helpers.UiElement;
import com.workfusion.rpa.helpers.UiElementCollection;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.Select;
import org.slf4j.Logger;

import javax.inject.Inject;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Set;

import static com.workfusion.rpa.helpers.RPA.*;
import static com.workfusion.rpa.helpers.UiSelectors.byImage;
import static com.workfusion.rpa.helpers.UiSelectors.byText;


@BotTask(requireRpa = true)
public class AutomateWebElements implements AdHocTask {

private final RpaRunner rpaRunner;
private final Logger logger;

@Inject
public AutomateWebElements(RpaFactory rpaFactory, Logger logger){
this.rpaRunner = rpaFactory
.builder(RpaDriver.UNIVERSAL)
.closeOnCompletion(true)
.build();
this.logger = logger;
}

@Override
public TaskRunnerOutput run(TaskInput taskInput) {

rpaRunner.execute(driver->{
this.executeJavaScriptExample(driver);
});

return taskInput.asResult()
.withColumn("example_bot_task_output", "completed_successfully");
}

private void executeJavaScriptExample(Driver driver){
RPA.openChrome("https://rpa-tutorial.s3.amazonaws.com/trainings/dnd/samples/dhtmlxTree/02_checkboxes/05_tree_checkboxes.html");
RPA.sleep(2000);
driver.switchDriver("chrome");
RPA.switchTo().defaultContent();

this.popAlert(driver," About to select all the Checkboxes of Books ");

// selecting a tree element and checking its branch
driver.executeScript(
"document.querySelector('#treeboxbox_tree table table tr:nth-child(1) > td > span').click();" +
"document.querySelector('body > table > tbody > tr:nth-child(1) > td:nth-child(2) > a:nth-child(9)').click();"
);
RPA.sleep(2000);

// invoking alert in JS and passing parameters to script
List<String> messages = new ArrayList<>(Arrays.asList("Hello ","From "));
driver.executeScript("alert(arguments[0][0] + arguments[0][1] + arguments[1])", messages,"JS");
RPA.sleep(2000);
RPA.switchTo().alert().dismiss();
// getting a node value using JS
Object element = driver.executeScript("return document.querySelector('body > p').textContent;");
}

private void popAlert(Driver driver,String popupMessage){
driver.switchDriver("chrome");
//Switch to default content inorder to work with alert if already on a IFrame
RPA.switchTo().defaultContent();
String script = popupMessage;
driver.executeScript("alert(arguments[0])",script);
RPA.sleep(3000);
RPA.switchTo().alert().accept();
}

}

You can use Java scripts to find an element by XPath:

Object value = driver().executeScript("return document.evaluate( '//body//div/iframe' ,document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null ).singleNodeValue;");

The document.evaluate() command is the Xpath evaluator in JavaScript. The signature of the function is as follows:

document.evaluate( xpathExpression, contextNode, namespaceResolver, resultType, result );

Mind the following parameters:

  • xpathExpression: a string containing the XPath expression to be evaluated.
  • contextNode: a node in the document against which the xpathExpression should be evaluated, including all its child nodes. The document node is the most commonly used.
  • NamespaceResolver: a function passed any namespace prefixes contained within xpathExpression that returns a string representing the namespace URI associated with that prefix.
  • resultType: a constant that specifies the desired result type to be returned as a result of the evaluation. The most commonly passed constant is XPathResult.ANY_TYPE that returns the results of the XPath expression as the most natural type.
  • result: if an existing XPathResult object is specified, it is reused to return the results. Specifying a null creates a new XPathResult object.

The actions you can perform are as follows:

  • Find any element on a page.

    WebElement element = $(By.id("some-id"));

    You can do the same thing using JavaScript:

    Object element = driver().executeScript("return document.getElementById('gsc-i-id1');")
  • Change the element attribute style. You can change the style property of elements to modify the element rendered view.

    executeScript("document.getElementById('text-4').style.borderColor = 'Red'");

    Coloring elements can also help you take screenshots with visual markers to identify problematic elements.

  • Get any value of valid element attributes.

    $(By.id("some-id")).getAttribute("Class");

    The code gets the value of the element class attribute with id = gsc-i-id1.

    You can execute the same thing in JavaScript:

    Object className = driver().executeScript("return document.getElementById('gsc-i-id1').getAttribute('class');");
  • Get frames in a browser. To know the total number of frames on a web page in JavaScript, use the following syntax:

    Object numberOfIframes = driver().executeScript("return document.frames.length;");

    :::tip For more information on iFrames, refer to Handle iFrames :::

  • Add an element to the DOM.

    driver().executeScript("var btn = document.createElement('BUTTON'); document.body.appendChild(btn);")
  • Get the window size. The size of inner browser window is the size of the window in which you see a web page:

    Object height = driver().executeScript("return window.innerHeight;");
    Object width = driver().executeScript("return window.innerWidth;");
  • Navigate to a different page.

    executeScript("window.location = 'https://wikipedia.org'");
  • Generate an alert pop window.

    executeScript("alert('hello world');");
  • Click an action.

    executeScript("arguments[0].click();", element);
  • Refresh a browser.

    executeScript("history.go(0)");
  • Get web page inner text.

    String sText = (String) driver().executeScript("return document.documentElement.innerText;").toString()
  • Get a web page title.

    String sText = (String) driver().executeScript("return document.title;").toString()
  • Scroll a page.

    driver().executeScript("window.scrollBy(0,150)");

Similarly, you can execute practically any JavaScript command.

Execute script asynchronously and return result

executeAsyncScript(script, arguments) allows executing the JavaScript code asynchrously.

Expand to view the code
import com.workfusion.bot.service.SecureEntryDTO;
import com.workfusion.odf2.compiler.BotTask;
import com.workfusion.odf2.core.cdi.Requires;
import com.workfusion.odf2.core.task.AdHocTask;
import com.workfusion.odf2.core.task.TaskInput;
import com.workfusion.odf2.core.task.output.TaskRunnerOutput;
import com.workfusion.odf2.core.webharvest.rpa.RpaDriver;
import com.workfusion.odf2.core.webharvest.rpa.RpaFactory;
import com.workfusion.odf2.core.webharvest.rpa.RpaRunner;
import com.workfusion.odf2.service.ControlTowerServicesModule;
import com.workfusion.odf2.service.vault.SecretsVaultService;
import com.workfusion.rpa.driver.Driver;
import com.workfusion.rpa.helpers.RPA;
import com.workfusion.rpa.helpers.UiElement;
import com.workfusion.rpa.helpers.UiElementCollection;
import org.openqa.selenium.Alert;
import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.Select;
import org.slf4j.Logger;
import javax.inject.Inject;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import static com.workfusion.rpa.helpers.RPA.*;
import static com.workfusion.rpa.helpers.UiSelectors.byImage;
import static com.workfusion.rpa.helpers.UiSelectors.byText;

@BotTask(requireRpa = true)
@Requires({ControlTowerServicesModule.class})
public class AutomateWebElements implements AdHocTask {

private final RpaRunner rpaRunner;
private final Logger logger;
private final SecretsVaultService secretsVault;

@Inject
public AutomateWebElements(RpaFactory rpaFactory, Logger logger, SecretsVaultService secretsVault){
this.rpaRunner = rpaFactory
.builder(RpaDriver.UNIVERSAL)
.closeOnCompletion(true)
.build();
this.logger = logger;
this.secretsVault = secretsVault;
}

@Override
public TaskRunnerOutput run(TaskInput taskInput) {

rpaRunner.execute(driver->{
this.executeScriptAsynchronouslyExample(driver);
});

return taskInput.asResult()
.withColumn("example_bot_task_output", "completed_successfully");
}

private void executeScriptAsynchronouslyExample(Driver driver){
String script = "var callback = arguments[arguments.length - 1];"+
"return callback(document.getElementsByTagName('a')[1].href) ";

RPA.openChrome("https://rpa-tutorial.s3.amazonaws.com/trainings/iframe/form.html");
this.popAlert(driver,"Asynchronous Example ");
Object result = driver.executeAsyncScript(script);
this.popAlert(driver," Result " + (String)result );
}

private void popAlert(Driver driver,String popupMessage){
driver.switchDriver("chrome");
//Switch to default content inorder to work with alert if already on a IFrame
RPA.switchTo().defaultContent();
String script = popupMessage;
driver.executeScript("alert(arguments[0])",script);
RPA.sleep(3000);
RPA.switchTo().alert().accept();
}

}