Execute JavaScript with Selenium WebDriver in C#
When attempting to use Selenium WebDriver to execute JavaScript in C#, developers often encounter difficulties locating the appropriate syntax. To address this, let's dive into the mechanics of executing JavaScript using C#.
In Java, executing JavaScript is accomplished through the JavascriptExecutor interface, while in C#, the corresponding interface is IJavaScriptExecutor. This simple change in naming reflects the goal of making the C# bindings feel natural to C# programmers.
To execute JavaScript in C#, utilize the following code snippet:
<code class="csharp">IWebDriver driver; // assume assigned elsewhere IJavaScriptExecutor js = (IJavaScriptExecutor)driver; string title = (string)js.ExecuteScript("return document.title");</code>
This code snippet retrieves the title of the web page using JavaScript. Note that the interface name, IJavaScriptExecutor, is used instead of JavascriptExecutor.
For a comprehensive overview of the WebDriver API for .NET, refer to the official documentation at the provided link.
The above is the detailed content of How to Execute JavaScript with Selenium WebDriver in C#?. For more information, please follow other related articles on the PHP Chinese website!