8.5. Executing Javascript

There are times when you may find it useful to execute a little Javascript directly within the browser to get the job done. You can use the evaluateJavascript() method of the PageObject class to do this. For example, you might need to evaluate an expression and use the result in your tests. The following command will evaluate the document title and return it to the calling Java code:

String result = (String) evaluateJavascript("return document.title");

Alternatively, you may just want to execute a Javascript command locally in the browser. In the following code, for example, we set the focus to the firstname input field:

        evaluateJavascript("document.getElementById('firstname').focus()");

And, if you are familiar with JQuery, you can also invoke JQuery expressions:

        evaluateJavascript("$('#firstname').focus()");

This is often a useful strategy if you need to trigger events such as mouse-overs that are not currently supported by the WebDriver API.