Skip to content

Instantly share code, notes, and snippets.

@jimevans
Created October 11, 2021 16:45
Show Gist options
  • Save jimevans/1b8e1f2050413573df24731d804d3c66 to your computer and use it in GitHub Desktop.
Save jimevans/1b8e1f2050413573df24731d804d3c66 to your computer and use it in GitHub Desktop.
Selenium C# JavaScript exception listening example
List<string> exceptionMessages = new List<string>();
IJavaScriptEngine monitor = new JavaScriptEngine(driver);
monitor.JavaScriptExceptionThrown += (sender, e) =>
{
exceptionMessages.Add(e.Message);
};
await monitor.StartEventMonitoring();
driver.Navigate.GoToUrl("<your site url>");
IWebElement link2click = driver.FindElement(By.LinkText("<your link text>"));
((IJavaScriptExecutor) driver).ExecuteScript("arguments[0].setAttribute(arguments[1], arguments[2]);",
link2click, "onclick", "throw new Error('Hello, world!')");
link2click.Click();
foreach (string message in exceptionMessages)
{
Console.WriteLine("JS exception message: {0}", message);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment