Not able to handle javascript alert from Selenium WebDriver

2,736 views
Skip to first unread message

Rana Banerjee

unread,
Jan 12, 2012, 4:21:41 AM1/12/12
to Selenium Users
Hi,

I am using Selenium 2.0 with FireFox WebDriver to test a web
application. I am facing some issues while handling JavaScript alerts.

I have done the following to capture the alert for one page.

Page 1
------------------
WebElement userNameElement = driver.findElement(By.xpath("//
input[@name='user_name']"));
userNameElement.sendKeys("");

WebElement element = driver.findElement(By.xpath("//
input[@name='submit']"));
element.click();

String alert = driver.switchTo().alert().getText();
driver.switchTo().alert().dismiss();

I am able to capture alert here.

Page 2
-----------------
WebElement amountElement = driver.findElement(By.xpath("//
input[@id='amount']"));
amountElement.sendKeys("");

WebElement element = driver.findElement(By.xpath("//
input[@name='submit']"));
element.click();

Alert alert = driver.switchTo().alert();
System.out.println("alert :::" + alert.getText());

Strangely, for Page2, the alert is not populated. While debugging, I
found that, the debug control is lost somewhere after I submit the
form. However, in the application to be tested, the alert appears.
Only after I click the alert manually, the debug control comes to
Alert alert = driver.switchTo().alert(); statement. But since I have
clicked on the alert already, the
org.openqa.selenium.NoAlertPresentException is thrown.

The only difference I can see between Page1 and Page2 code, is that
the former has the javascript function inside the JSP page, the latter
has it in an external .js file.

Any help is much appreciated. Also, please let me know if you need any
further information.

Thanks,
Rana

Rana Banerjee

unread,
Jan 16, 2012, 6:08:50 AM1/16/12
to Selenium Users
Hi,
 
Is there any update on this? This is kind of urgent.
 
Thanks in advance,
Rana Banerjee

Mike Riley

unread,
Jan 17, 2012, 5:54:00 PM1/17/12
to Selenium Users
I was having problems with alerts myself using WebDriverBackedSelenium
with the Selenium API methods it provides. I ended up writing a few
methods to handle them that look like the Selenium 1.0 API versions,
but use the WebDriver API instead. The only real difference I see
between your code and mine is that I am doing an accept().

Here is the code if it helps:

/**
* This is identical to the selenium.isAlertPresent() method for
* WebDriverBackedSelenium, in that it checks to see if an alert
message
* is present, except this one works. It uses WebDriver methods
to check to
* see if a JavaScript alert() message is on the screen.
* @return This will return true is an alert message is on the
screen.
*/
public boolean isAlertPresent()
{
try
{
driver.switchTo().alert();
return true;
} // try
catch (NoAlertPresentException Ex)
{
return false;
} // catch
} // isAlertPresent()

/**
* This is identical to the selenium.getAlert() method for
* WebDriverBackedSelenium, in that it gets the text of the alert
message
* and it clicks the OK button to make it go away, except this one
works.
* @return String with the text of the alert message in it.
*/
public String getAlert()
{
Alert alert = driver.switchTo().alert();
String str = alert.getText();

alert.accept();
return str;
} // getAlert()

/**
* This will wait until a JavaScript alert() message is present,
or until
* the timeoutMSec expires.
* @param timeoutMSec The time to wait before throwing an
exception showing
* no alert() message is present.
* @throws Exception
* @see <a href="http://groups.google.com/group/selenium-users/
browse_thread/thread/e559b59a513630c8/ff4ca846f6c01b5e?lnk=gst&q=alert+
%26+driver#">Post by Mark Collin</a>
*/
public void waitForAlert(int timeoutMSec) throws Exception
{
startTimer(timeoutMSec);
while (!timerExpired && !isAlertPresent())
{
pause(100); // Delay .1 seconds
} // while

if (timerExpired)
throw new Exception("No alert was seen in " + timeoutMSec
+ "MSec.");
else
timer.stop();
} // waitForAlert(int timeoutMSec) throws Exception


On Jan 16, 3:08 am, Rana Banerjee <ranarbaner...@gmail.com> wrote:
> Hi,
>
> Is there any update on this? This is kind of urgent.
>
> Thanks in advance,
> Rana Banerjee
>

Rana Banerjee

unread,
Jan 19, 2012, 3:49:22 AM1/19/12
to Selenium Users
Hi Mike,

Thanks for getting back. I have tried WebDriver and
WebDriverBackedSelenium both along with the code you provided. Still
no luck.

The issue here is, once I submit the form, the control does not move
to next statement, which is
[Alert alert = driver.switchTo().alert(); ]. However the alert appears
on the webpage. Until I click manually on the alert, the control does
not move to next statement. But, as I have clicked on the alert, the
driver cannot switch to it, thus throwing a NoSuchAlertException.

Ideally, I should be able to capture the alert after I submit the form
and also click on the alert from the application code itself.

In the example Page 1, I can do that, but not in Page 2. Only
difference between these two pages is, in page 2, the javascript
onClick() function is in an external .js file.

I have no clue why this is happening. Is this a Selenium bug?

Regards,
Rana Banerjee
> > > Rana- Hide quoted text -
>
> - Show quoted text -

Rana Banerjee

unread,
Mar 9, 2012, 5:29:53 AM3/9/12
to Selenium Users
Hi,

I have digged a little deeper on this issue. This occurs only in
Firefox browser and it's pretty consistent through all the major
versions of Firefox.

In IE 7 and 8, this does not happen and without making any code
change, I am able to handle alerts and alert text.

In Firefox, however, if there are multiple popups, after clicking on
the first alert manually, it's able to handle the second popups.

It clearly seems to be a Selenium WebDriver bug. Can anybody comment
on when we can expect the issue to be resolved?

Regards,
Rana Banerjee
> > - Show quoted text -- Hide quoted text -

Shaba K

unread,
Mar 9, 2012, 6:26:00 AM3/9/12
to seleniu...@googlegroups.com
See if adding switchTo().frame() helps ?

But am surprised i just used the same bit as you & it worked fine ..

-Shabana


--
You received this message because you are subscribed to the Google Groups "Selenium Users" group.
To post to this group, send email to seleniu...@googlegroups.com.
To unsubscribe from this group, send email to selenium-user...@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/selenium-users?hl=en.


Mike Riley

unread,
Mar 9, 2012, 2:41:16 PM3/9/12
to Selenium Users
File an issue with a sample HTML and Selenium code to reproduce it.
http://code.google.com/p/selenium/issues

Mike

Jon Williams

unread,
Mar 9, 2012, 6:00:06 PM3/9/12
to seleniu...@googlegroups.com
In my opinion, instead of doing this:

 try  { 
            driver.switchTo().alert(); 
            return true; 
        } 


Do this instead:

 try  { 
            if ( driver.switchTo().alert() != null ) {
                  Alert al = driver.switchTo().alert();
                     al.dismiss();
            return true; 
             }
        } 


-jon

Mike Riley

unread,
Mar 12, 2012, 3:10:11 PM3/12/12
to Selenium Users
Or better yet:

try {
Alert al = driver.switchTo().alert();
if ( al != null )
{
al.dismiss();
return true;
}
}

No need to execute the methods twice...

Mike

Rana Banerjee

unread,
Apr 6, 2012, 2:47:17 AM4/6/12
to Selenium Users
Hello,

In my first email, I have already said that I have incorporated
driver.switchTo().alert(). The firefox browser, sometimes, cannot
recognize the Alert itself, and hence causing this error. The same
code runs fine with IE 7.0 + versions.

Clearly it seems to be a Selenium bug for the way it interacts with
Firefox. I have tried to handle the alert for the specific page (where
it's causing trouble) by using Webdriver and WebDriverBackedSelenium.
But it kept on trying to find the Alert and the code execution halts
there. The moment I manually click OK in the Alert, the code starts
executing again but it cannot find the Alert since I have dismissed it
already.

This issue is hard to replicate, as there is no clear indication when
and where this will happen. For the specific page where it's
happening, is a part of an Enterprise Web Application, hence I cannot
really post it here.

Thanks anyways for your assistance.

Regards,
Rana

Mark Collin

unread,
Apr 6, 2012, 4:13:18 AM4/6/12
to seleniu...@googlegroups.com
Is it definitely a JavaScript alert, and not an OS level dialogue?

Rana Banerjee

unread,
Apr 19, 2012, 5:26:13 AM4/19/12
to Selenium Users
Hi Mike,

Yes it's definitely a Javascript alert written in an external .js
file.

Regards,
Rana Banerjee

Mark Collin

unread,
Apr 19, 2012, 5:55:54 AM4/19/12
to seleniu...@googlegroups.com
Without more information we cannot help, can you show us your test code?

Nimesh.T.Prajapati

unread,
Apr 19, 2012, 6:20:50 AM4/19/12
to seleniu...@googlegroups.com
Hi,

I'm also facing same issue, not recognizing javascript msg.

In my case, I'm reaching to iframe than returning back...


Thread.sleep(10000L);
wd.findElement(By.id("btnEdit")).click();

Thread.sleep(2000L);
wd.switchTo().frame("agentiframe");
WebElement editable=wd.switchTo().activeElement();

//Forcing the script to run without input

String script="validateForm();";
((JavascriptExecutor)wd).executeScript(script);
Alert alert=wd.switchTo().alert();
System.out.println(alert.getText());
alert.accept();
//-------------------------------------------------

//Setting up file name
String file=null;
file="C:\\screenshot.png";
//file="c:\\lan.txt";
//-------------------------------------------------

//
editable.findElement(By.id("ImgName")).sendKeys(file);
System.out.println(wd.findElement(By.id("imgUpload")).getAttribute("style"));
String script1="validateForm();";
((JavascriptExecutor)wd).executeScript(script1);
//String status=(java.lang.String) ((JavascriptExecutor)wd).executeScript("return document.getElementsById(imgUpload)");
System.out.println(wd.findElement(By.id("imgUpload")).getAttribute("style"));
try
{

if(wd.findElement(By.id("errMsg")).isEnabled() || wd.findElement(By.id("errMsg")).isDisplayed())
System.out.println(wd.findElement(By.id("errMsg")).getText());
}
catch(NoSuchElementException e)
{
System.out.println("No element");
wd.switchTo().defaultContent();
}

//((JavascriptExecutor)wd).executeScript("editAgentContactInfo();");
wd.findElement(By.xpath(".//*[@id='submitDiv']/button[1]")).click();
Selenium selenium1=new WebDriverBackedSelenium(wd,wd.getCurrentUrl());
System.out.println(selenium1.isAlertPresent());

--
You received this message because you are subscribed to the Google Groups "Selenium Users" group.
To post to this group, send email to seleniu...@googlegroups.com.
To unsubscribe from this group, send email to selenium-user...@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/selenium-users?hl=en.




--
Nimesh T. Prajapati
"Quality does matter..."

Nimesh.T.Prajapati

unread,
Apr 19, 2012, 6:55:19 AM4/19/12
to seleniu...@googlegroups.com
Hi,

called script having following code:
new ajaxRequest(url,qs,function(reqobj){
13989 resp = trim(reqobj.responseText);
13990 if(resp > 1)
13991 alert("Data added successfully...!");
13992 else
13993 alert("Data updated successfully...!");
13994 },false); 



Disregard typo issues if found...

Nimesh.T.Prajapati

unread,
Apr 21, 2012, 7:37:54 AM4/21/12
to seleniu...@googlegroups.com
Hi,

Any Que?

Nimesh.T.Prajapati

unread,
Apr 23, 2012, 12:37:03 AM4/23/12
to seleniu...@googlegroups.com
Hi,

Any can help me out from moving to frame and backing up?

Michael Yang

unread,
Apr 25, 2012, 2:11:32 PM4/25/12
to seleniu...@googlegroups.com
In firefox, the webdriver is blocked in the thread by the Alert dialog, that's why you can not move to next statement when you do the click. You can wrap up the click action and dispatch it to a thread, so that the webdriver in the main thread can continue with confirming on the alert dialog.

something like this:

Thread t = new Thread(new Runnable(){
     public void run(){
          webdriver.findElement(xpath).click();
     }
});
t.start();
webdriver.switchTo().alert().accept();
== Life is a Project ==

Premila

unread,
Apr 25, 2012, 6:51:35 PM4/25/12
to Selenium Users
Thank you, Yang. I faced a similar issue and your solution worked.




On Apr 25, 11:11 am, Michael Yang <michael....@gmail.com> wrote:
> In firefox, the webdriver is blocked in the thread by the Alert dialog,
> that's why you can not move to next statement when you do the click. You
> can wrap up the click action and dispatch it to a thread, so that the
> webdriver in the main thread can continue with confirming on the alert
> dialog.
>
> something like this:
>
> Thread t = new Thread(new Runnable(){
>      public void run(){
>           webdriver.findElement(xpath).click();
>      }});
>
> t.start();
> webdriver.switchTo().alert().accept();
>
> On Mon, Apr 23, 2012 at 12:37 AM, Nimesh.T.Prajapati
> <nimesh2...@gmail.com>wrote:
>
>
>
> > Hi,
>
> > Any can help me out from moving to frame and backing up?
>
> > On Sat, Apr 21, 2012 at 5:07 PM, Nimesh.T.Prajapati <nimesh2...@gmail.com>wrote:
>
> >> Hi,
>
> >> Any Que?
>
> >> On Thu, Apr 19, 2012 at 4:25 PM, Nimesh.T.Prajapati <nimesh2...@gmail.com
> >> > wrote:
>
> >>> Hi,
>
> >>> called script having following code:
> >>> new ajaxRequest(url,qs,function(reqobj){
> >>> 13989 resp = trim(reqobj.responseText);
> >>> 13990 if(resp > 1)
> >>> 13991 alert("Data added successfully...!");
> >>> 13992 else
> >>> 13993 alert("Data updated successfully...!");
> >>> 13994 },false);
>
> >>> *Disregard typo issues if found...*

Keerthi Srujana

unread,
May 23, 2018, 12:45:24 PM5/23/18
to Selenium Users
I am facing a same issue as mentioned below but with Chrome . Any help would be much appreciated.

Thanks,
K

Shawn McCarthy

unread,
May 23, 2018, 5:50:04 PM5/23/18
to Selenium Users
Keerthi You probably want to open a new thread. This one is 6 years old...
Reply all
Reply to author
Forward
0 new messages