Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Execute JavaScript using Selenium WebDriver in C#

How is this achieved? Here it says the java version is:

WebDriver driver; // Assigned elsewhere JavascriptExecutor js = (JavascriptExecutor) driver; js.executeScript("return document.title"); 

But I can't find the C# code to do this.

like image 217
JontyMC Avatar asked Jun 03 '11 16:06

JontyMC


People also ask

How can JavaScript be directly executed on WebDriver?

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.

Can we execute JavaScript on browser with Selenium?

You an use selenium to do automated testing of web apps or websites, or just automate the web browser. It can automate both the desktop browser and the mobile browser. Selenium webdriver can execute Javascript. After loading a page, you can execute any javascript you want.

Which of the following Selenium code can execute JavaScript directly?

a) executeScript This method executes JavaScript in the context of the currently selected window or frame in Selenium.


2 Answers

The object, method, and property names in the .NET language bindings do not exactly correspond to those in the Java bindings. One of the principles of the project is that each language binding should "feel natural" to those comfortable coding in that language. In C#, the code you'd want for executing JavaScript is as follows

IWebDriver driver; // assume assigned elsewhere IJavaScriptExecutor js = (IJavaScriptExecutor)driver; string title = (string)js.ExecuteScript("return document.title"); 

Note that the complete documentation of the WebDriver API for .NET can be found at this link.

like image 123
JimEvans Avatar answered Sep 29 '22 20:09

JimEvans


I prefer to use an extension method to get the scripts object:

public static IJavaScriptExecutor Scripts(this IWebDriver driver) {     return (IJavaScriptExecutor)driver; } 

Used as this:

driver.Scripts().ExecuteScript("some script"); 
like image 41
Morten Christiansen Avatar answered Sep 29 '22 20:09

Morten Christiansen