Andy Williams Andy Williams - 2 months ago 31
Javascript Question

How to handle alert pop up with JavaScript? Selenium Webdriver

Selenium WebDriver 2.53.1.1
Visual Studio 2015
C#

The application I am testing has Alert Pop Ups which I handle with the following bit of code without problem

ts.getDriver().SwitchTo().Alert().Accept();


However I have ran into a new issue. Some of my webelements have issues of not being found anymore and therefore I have to run JavaScript to execute the web element (please see code below for handling the web element)

public void SelectHREFCID()
{
IJavaScriptExecutor js = ts.getDriver() as IJavaScriptExecutor;
js.ExecuteScript("arguments[0].click()",hrefCID);
try
{
ts.getDriver().SwitchTo().Alert().Accept();
}
catch (NoAlertPresentException)
{
// do nothing...
}// Have to use this to find the hyperlink!
}


The only problem is immediately after js.ExecuteScript line runs, the Pop Up Displays and my Alert().Accept() line of code never fires off after this so the program just stops there with the pop up. I ran this line by line in debug and can't can't step to the next line once I execute the js.ExecuteScript line. Any advice on how to handle this?

UPdate At this point in my code (js.ExecuteScript))
enter image description here

, as soon as this line of code is executed i see this

enter image description here

Once this pop up displays My Selenium Code does not continue into the try catch statement to handle the Alert

Latest update as of 9/9

I tried the alert handle both ways
enter image description here
enter image description here

But my selenium code stops execution at the point of the pop up firing off

js.ExecuteScript("arguments[0].click().hrefCID);


**UPDATE 09/12****

I updated my window.alert and this resolved the issue (to confirm)

IJavaScriptExecutor js = ts.getDriver() as IJavaScriptExecutor;
js.ExecuteScript("window.confirm = function(){return true;}");
js.ExecuteScript("arguments[0].click()",hrefCID);
// js.ExecuteScript("window.alert = function() { return true;}");

Answer

I think this alert blocks the code execution, you should execute this script before click to override the confirmBox function using js as :-

js.ExecuteScript("window.confirm = function() { return true;}")

After that execute as below to perform click on button :-

js.ExecuteScript("arguments[0].click()",hrefCID);