Script execution methods
So, as stated above, there are two methods that can execute your JS script: executeScript and executeAsyncScript. All of them have a common syntax:
Let’s take a closer look at each of them.
If your script returns any value you can assign it to a variable, using types as follows:
- WebElement – if your script returns an HTML element
- Double – if it’s a decimal number
- Long for non-decimal numbers
- Boolean for a boolean value
- String – all the other cases
Your script can also return List<Object> or Map<String, Object> using the rules above for Object type. It also can assign the null value if the returned value is null or no value returned.
For example, you can refresh a browser window by the following code:
For all of our examples, we will use the following structure of our test class which you can get from our git repository of this blog post.
One of the interesting ways of having an output is alert messages. You will see something like this:
Interestingly enough, we can temporarily change the style of an element on a page. It can be useful when you want to highlight some important elements to have pretty screenshots in your automated reports.
Let’s see how we can use executeAsyncScript method to manage waits. For example, if we want to open our page and wait for 5 seconds for the page to load:
In this example we used both the executeScript and executeAsyncScript methods, as well as made use of custom arguments.