Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to execute JavaScript in Ruby written Webdriver test?

Is there a known solution to perform Eval (Javascript execution) in Webdriver, Ruby bindings?

The equivalent of the following example in Java.

 WebElement element = driver.findElement(By.id( "foo" ));
 String name = (String) ((JavascriptExecutor) driver).executeScript(
 "return arguments[0].tagName" , element)
like image 994
Yulia Avatar asked Sep 27 '11 07:09

Yulia


People also ask

How can you execute Javascript code in Webdriver?

Selenium webdriver can execute Javascript. After loading a page, you can execute any javascript you want. A webdriver must be installed for selenium to work. All it takes to execute Javascript is calling the method execute_script(js) where js is your javascript code.

What is the use of Javascript executed in Selenium Webdriver?

What is JavascriptExecutor in Selenium? In simple words, JavascriptExecutor is an interface that is used to execute JavaScript with Selenium. To simplify the usage of JavascriptExecutor in Selenium, think of it as a medium that enables the WebDriver to interact with HTML elements within the browser.

How do you read a Javascript variable in Selenium Webdriver?

We can read Javascript variables with Selenium webdriver. Selenium can run Javascript commands with the help of executeScript method. The Javascript command to be executed is passed as an argument to the method. Also we have to add the statement import org.

Which of the following Selenium code can execute Javascript directly?

JavaScriptExecutor is an Interface that helps to execute JavaScript through Selenium Webdriver. JavaScriptExecutor provides two methods “executescript” & “executeAsyncScript” to run javascript on the selected window or current page.


2 Answers

Thank you for posting this answer. It helped me a lot. I was googling the whole day to figure out how to execute JavaScript code within Ruby.

@driver.execute_script("arguments[0].scrollIntoView(true);", element )

By doing so, I was able to scroll into the specific element before click event. This might help others a bit.

I had to use JavaScript alternative because for some reason this wasn't: working for me element.location_once_scrolled_into_view

Thanks.

like image 111
eyumay Avatar answered Sep 20 '22 08:09

eyumay


The equivalent Ruby would be:

 name = driver.execute_script("return arguments[0].tagName" , element)

(to get the tag name you could also just call element.tag_name)

like image 32
jarib Avatar answered Sep 22 '22 08:09

jarib