Home  >  Article  >  Web Front-end  >  How Do I Execute JavaScript with Selenium WebDriver in C#?

How Do I Execute JavaScript with Selenium WebDriver in C#?

Patricia Arquette
Patricia ArquetteOriginal
2024-10-19 06:05:02674browse

How Do I Execute JavaScript with Selenium WebDriver in C#?

Executing JavaScript with Selenium WebDriver in C#

The question poses an inquiry regarding the process of executing JavaScript using Selenium WebDriver in C#, specifically related to finding the corresponding C# code for executing a Java-based script.

Java Code:

<code class="java">WebDriver driver; // Assigned elsewhere
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("return document.title");</code>

C# Equivalent:

In C#, the equivalent code is as follows:

<code class="csharp">IWebDriver driver; // Assume assigned elsewhere
IJavaScriptExecutor js = (IJavaScriptExecutor)driver;
string title = (string)js.ExecuteScript("return document.title");</code>

Notes:

  • The .NET language bindings adhere to the principle of providing a natural coding experience for each language. Therefore, method and property names may differ slightly from the Java bindings.
  • The ExecuteScript method in C# returns an object. To work with string results, explicitly cast the return value to a string.
  • For comprehensive documentation on the Selenium WebDriver API for .NET, refer to the provided link in the reference answer.

The above is the detailed content of How Do I Execute JavaScript with Selenium WebDriver in C#?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn