Execute JavaScript using Selenium WebDriver in C# Execute JavaScript using Selenium WebDriver in C# selenium selenium

Execute JavaScript using Selenium WebDriver in C#


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 elsewhereIJavaScriptExecutor 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.


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");


the nuget package Selenium.Support already contains an extension method to help with this. Once it is included, one liner to executer script

  Driver.ExecuteJavaScript("console.clear()");

or

  string result = Driver.ExecuteJavaScript<string>("console.clear()");