Monday, 17 March 2014

How to execute Javascript in selenium webdriver in C#.Net?

IJavaScriptExecutor interface provided in C# selenium API is very powerful
feature. We can execute any javascript code on the current web page opened by
Selenium Webdriver using IJavaScriptExecutor 

Complete example in C#.Net to execute Java script is given below.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using OpenQA.Selenium;
using OpenQA.Selenium.Firefox;
using OpenQA.Selenium.Chrome;
using OpenQA.Selenium.IE;
//for SelectElement
using OpenQA.Selenium.Support.UI;
using System.Collections.ObjectModel;
//for events - Actions
using OpenQA.Selenium.Interactions;
//screenshot
using System.Drawing.Imaging;
namespace Abc
{
class Program
{
static void Main(string[] args)
{
//IWebDriver x = new InternetExplorerDriver(@"F:\selenium\csharp");
//IWebDriver x = new FirefoxDriver();
IWebDriver driver=null;
try
{
 driver = new ChromeDriver(@"F:\selenium\csharp");
 driver.Url = "http://register.rediff.com/register/register.php";
 driver.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(20));
 driver.Manage().Timeouts().SetPageLoadTimeout(TimeSpan.FromSeconds(50));
 driver.Manage().Window.Maximize();
 driver.Navigate();

 String Javascript = "return document.documentElement.innerText;";

 String t = ((IJavaScriptExecutor)driver).ExecuteScript(Javascript).ToString();

 //Above code will return the html source of the page 
 Console.WriteLine(t);


}
catch(Exception e){
Console.WriteLine("Exception ....*********"+e.ToString());
}
finally{
Thread.Sleep(2000);
driver.Quit();
Console.ReadLine();
}
}
}
}




What do you think on above selenium topic. Please provide your inputs and comments. You can write to me at reply2sagar@gmail.com

1 comment:

  1. Hi Sagar,
    Thank you very much for your material.It's very useful and easily understandable for all.

    ReplyDelete

Buy Best Selenium Books