Skip to main content
Version: 10.2.4

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.

<?xml version="1.0" encoding="UTF-8"?>
<config xmlns="http://web-harvest.sourceforge.net/schema/1.0/config" scriptlang="groovy">
<robotics-flow>
<robot driver="chrome" name="web" close-on-completion="true">
<script><![CDATA[

open("https://rpa-tutorial.s3.amazonaws.com/trainings/dnd/samples/dhtmlxTree/02_checkboxes/05_tree_checkboxes.html")
sleep(2000)

// selecting a tree element and checking its branch
executeJavaScript(
"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();"
)
sleep(2000)

// invoking alert in JS and passing parameters to script
def messages = ['Hello ', 'from ']
executeJavaScript("alert(arguments[0][0] + arguments[0][1] + arguments[1])", messages, 'JS')
sleep(2000)
dismiss()

// getting a node value using JS
element = executeJavaScript("return document.querySelector('body > p').textContent;")

]]></script>
</robot>
</robotics-flow>
<export include-original-data="false">
<single-column name="paragraph" value="${element}"/>
</export>
</config>

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

value = 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.

    element = $(byId('some-id'))

    You can do the same thing using JavaScript:

    element = 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.

    $(byId('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:

    className = 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:

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

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

  • Add an element to the DOM.

    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:

    height = executeScript("return window.innerHeight;")
    width = 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.

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

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

    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.

<?xml version="1.0" encoding="UTF-8"?>
<config xmlns="http://web-harvest.sourceforge.net/schema/1.0/config" scriptlang="groovy">

<robotics-flow>
<robot driver="chrome">
<script><![CDATA[

String script = """ var callback = arguments[arguments.length - 1];
return callback(document.getElementsByTagName('a')[1].href) """

open("https://rpa-tutorial.s3.amazonaws.com/trainings/iframe/form.html")
def result = driver().executeAsyncScript(script)
sys.defineVariable("result", result)
]]></script>
</robot>
</robotics-flow>
<export include-original-data="true">
</export>

</config>