Executing JavaScript in Selenium WebDriver

How to run JavaScript in your browser directly from Selenium WebDriver and when to use it

Courtney Zhan

--

Modern websites use JavaScript heavily. This can make some interactions tricky. Selenium has built-in support to execute JavaScript, which can be handy for those difficult automation scenarios.

A Simple Example

Let’s start with the simplest JS action: show an alert with some text.

it "Simple JS" do
driver.navigate.to("https://travel.agileway.net")
driver.execute_script("alert('Hello JS from Selenium')")
end

Here is what the execution looks like:

While this alert JS offers no value to test automation, this quick example shows that Selenium supports executing arbitrary JavaScript; which can be powerful.

Passing Object to JavaScript in Selenium Scripts

In the article “Optimize Selenium WebDriver Automated Test Scripts: Speed”, my father showed an example of entering a very large text blobusing JavaScript.

--

--