Search code examples
c#seleniumselenium-webdriveronclicklistener

Need working example of EventFiringWebDriver and OnFindingElement or OnElementClicked usage in Selenium C#?


I am a novice to both Selenium and C#. Can someone please help me with an working example of how to write a message to a log file or Console.WriteLine upon clicking an element or finding an element using EventFiringWebDriver? I am looking for C# and not Java.


Solution

  • Using Statements:

    using OpenQA.Selenium.Remote;
    using OpenQA.Selenium.Support.Events;
    using OpenQA.Selenium.Support.Extensions;
    using OpenQA.Selenium;
    using OpenQA.Selenium.Chrome;
    using OpenQA.Selenium.Firefox;
    using OpenQA.Selenium.IE;
    

    Initialize the WebDriver:

    IWebDriver webDriver = new FirefoxDriver();
    var firingDriver = new EventFiringWebDriver(WebDriver);
    
    firingDriver.ExceptionThrown +=
        new EventHandler<WebDriverExceptionEventArgs>(firingDriver_ExceptionThrown);
    
    firingDriver.ElementClicked +=
        new EventHandler<WebElementEventArgs>(firingDriver_ElementClicked);
    
    firingDriver.FindElementCompleted +=
        new EventHandler<FindElementEventArgs>(firingDriver_FindElementCompleted);
    
    webDriver = firingDriver; // this is important!
    

    Logging Methods:

    static void firingDriver_ExceptionThrown(object sender, WebDriverExceptionEventArgs e)
    {
        Console.WriteLine(e.ThrownException.Message);
    }
    
    static void firingDriver_ElementClicked(object sender, WebElementEventArgs e)
    {
        Console.WriteLine(e.Element);
    }
    
    static void firingDriver_FindElementCompleted(object sender, FindElementEventArgs e)
    {
        Console.WriteLine(e.FindMethod);
    }