Skip to content
This repository has been archived by the owner on Nov 29, 2018. It is now read-only.

Handle alerts and prompts #27

Closed
lukeis opened this issue Mar 2, 2016 · 117 comments
Closed

Handle alerts and prompts #27

lukeis opened this issue Mar 2, 2016 · 117 comments

Comments

@lukeis
Copy link
Member

lukeis commented Mar 2, 2016

Originally reported on Google Code with ID 27

Many sites use javascript alerts and prompts to communicate with the user.
It should be possible to test these using WebDriver.

Reported by simon.m.stewart on 2007-10-31 16:55:04

@lukeis
Copy link
Member Author

lukeis commented Mar 2, 2016

Yes, this will be a great feature!!
Also have a look at watij!!

Reported by turturiellomartino on 2008-04-22 15:50:11

@lukeis
Copy link
Member Author

lukeis commented Mar 2, 2016

Yes it would be great!
I'm using WebDriver (r280) to test a website and I am stuck because of a javascript
"confirm" modal window. Is there any known workaround that could help me? I just want
to go through this window by automatically clicking "ok", I actually do not care
about what is displayed. Selenium is able to do that but I prefer WebDriver. Thanks
for your help!

Reported by achautard on 2008-06-04 15:06:49

@lukeis
Copy link
Member Author

lukeis commented Mar 2, 2016

Remark: login-dialog or download-dialog belongs to this sort of prompts too...
        (a workaround with sendKeys(Keys.ESCAPE) doesn't work)

Reported by George.Herczeg on 2008-08-22 06:53:19

@lukeis
Copy link
Member Author

lukeis commented Mar 2, 2016

A click on a <a href='...' target='_blank'> opens new windows/tabs...

A click on a <a href='javascript:openpopup();' onclick='return openpopup();'>
   opens new popups

It should be possible to prevent/control opening new windows/tabs/popup.

Possibilities:
 1. override target attribut
 2. callback for controlling new windows/tabs/popup
    (like IE: CHtmlView::OnNewWindow2, CHtmlView::OnBeforeNavigate2
     or CHtmlView::OnShowMessage)
 3. an excellent solution would be the possibility to redirect to my own window, 
    like the IE-code:
    void CMyHtmlView::OnNewWindow2(LPDISPATCH* ppDisp, BOOL* Cancel)
    {
       SetSilent(TRUE);
       *ppDisp = this->m_pBrowserApp;
    }

Reported by George.Herczeg on 2008-08-22 07:13:49

@lukeis
Copy link
Member Author

lukeis commented Mar 2, 2016

This bug is to do with handling alerts, prompts and "confirms" from javascript. The
aim is for this to appear as something like:

Alert alert = driver.switchTo().alert();
alert.accept();

Preventing new windows from being opened is outside the scope of this issue.

Reported by simon.m.stewart on 2008-08-22 09:23:18

@lukeis
Copy link
Member Author

lukeis commented Mar 2, 2016

The following workaround made it for me:

((JavascriptExecutor) driver).executeScript("window.confirm = function(msg) { return
true; }");

Reported by achautard on 2008-12-18 19:38:52

@lukeis
Copy link
Member Author

lukeis commented Mar 2, 2016

Will this include support for modal dialogs?  I'm referring to the javascript
function showModalDialog (I think IE, FF and safari all support it now)

Reported by steveccrp on 2009-01-20 02:52:59

@lukeis
Copy link
Member Author

lukeis commented Mar 2, 2016

Do you have plans to implement this soon, because it has become an important issue
for us?  I need to know when an alert has been popped up and dismiss it.  It would
be
nice to read the alert's text too.  I'm starting to think about checking out the
source and having a go myself.  Do you think it's a tough job?

Reported by jjimjam on 2009-02-09 15:32:54

@lukeis
Copy link
Member Author

lukeis commented Mar 2, 2016

I'd be delighted if someone else had a go at making this work :) As a short term fix,
you may consider overriding "window.alert" using the JavascriptExecutor.

Reported by simon.m.stewart on 2009-02-09 18:07:43

@lukeis
Copy link
Member Author

lukeis commented Mar 2, 2016

I started automating a web application using webdriver.During execution of some
testcases i am getting java alerts.When i used
Alert alert = driver.switchTo().alert();
alert.accept();
I am getting error message The method alert() is undefined for the type WebDriver.
TargetLocator. Is the Issue no 27 is fixed?.Can you tell me what was the problem in
my code.


With Thanks & Regards,

Mayur Bongirwar

Reported by mpbongirwar on 2009-04-08 13:35:28

@lukeis
Copy link
Member Author

lukeis commented Mar 2, 2016

would be great if we could handle this without overrriding the window.confirm. After
all this is the point of webdriver, to test this stuff. 

Reported by bertvanbrakel on 2009-04-20 15:26:21

@lukeis
Copy link
Member Author

lukeis commented Mar 2, 2016

Would be great to help automate testing!

Reported by virtix on 2009-04-24 19:53:44

@lukeis
Copy link
Member Author

lukeis commented Mar 2, 2016

as a hack you could also inject some javascript to make an html POST or GET when the
js popup is shown. below is just my thoughts, haven't tried it yet

something like:

window.confirm=function(msg){
var winId = window._webdriver_handle_id;
var http = new XMlHttpRequest();
//set location to listening server
//send alert msg, win id
//return true/false
}

The window id is put in the window by webdriver. You'll have to write some  code to
do this. This id allows you to identify what window the alert came from, so you can
check the correct window called it. You then validate the msg. 

You'll also need to open up an http listener in your test code.


Reported by bertvanbrakel on 2009-04-25 13:03:16

@lukeis
Copy link
Member Author

lukeis commented Mar 2, 2016

Has anyone found a workaround for this?  I've tried all the suggestions on this page,
but none of them get me past the javascript alert boxes.

Thanks!

Reported by shortdarkandhandsome on 2009-05-05 17:19:09

@lukeis
Copy link
Member Author

lukeis commented Mar 2, 2016

Issue 193 has been merged into this issue.

Reported by simon.m.stewart on 2009-06-03 09:57:03

@lukeis
Copy link
Member Author

lukeis commented Mar 2, 2016

We are starting up a testing process with selenium and webdriver.
A solution to this issue would save us a lot of work, because we have a few screens
using alerts/confirmations/modalWindows.

Is there a description of a workaround?


Reported by olafvanhemelryck on 2009-06-16 09:52:19

@lukeis
Copy link
Member Author

lukeis commented Mar 2, 2016

Here's what I use to work around the alert problem with the firefox driver.  I don't
have any other modal windows in my app, but I imagine the solution would be similar
for them.   I'm not that happy with it but it does allow me to detect alerts, check
the text and dismiss them.   

Actually it changes what happens when the js alert function is called, so you won't
see an alert box at all.    Also it won't work like a modal alert and block following
messages.  

registerAlertHack() has to be called just once for each page.   However I don't
really know when the page changes in my app, so I call it the whole time in
'sendMessage'.


  driver = new FirefoxDriver()
  {
    protected String sendMessage(Class<? extends RuntimeException> aClass, Command
command)
    {
      String r = super.sendMessage(aClass, command);
      registerAlertHack();
      return r;
    }
  };



private void registerAlertHack()
{
  if (driver != null)
  {
    String js = "if (window.alert.myAlertText == undefined) {window.alert.myAlertText
= null;  window.alert = function(msg){ window.alert.myAlertText = msg; };}";
    ((JavascriptExecutor)driver).executeScript(js);
  }
}

public boolean jsAlertExists()
{
  return  getJsAlertText() != null;
}

public String getJsAlertText()
{
  Object txt = ((JavascriptExecutor)driver).executeScript("return
window.alert.myAlertText;");
  return (String)txt;
}

public void clickJsAlert()
{
  ((JavascriptExecutor)driver).executeScript("window.alert.myAlertText = null;");
}

Reported by jjimjam on 2009-06-16 11:58:45

@lukeis
Copy link
Member Author

lukeis commented Mar 2, 2016

We are starting up a testing process with selenium and webdriver.
A solution to this issue would save us a lot of work, because we have a few screens
using alerts/confirmations/modalWindows.

Please let me know if any updates on this or something which I can implement myself
on 
internetexplorerdriver?.

Reported by sandeep.maloth on 2009-07-26 13:08:11

@lukeis
Copy link
Member Author

lukeis commented Mar 2, 2016

I tweaked the workaround that jjimjam submitted to make it a little simpler (for the
JavaScript novice like myself).  In essence you have to know when you will be
generating an alert or confirmation window and you have to know what you want to do
with that window.  So, sometime before the confirmation/alert is generated, just run
this line of code if you want to click OK on a confirm window:
((JavascriptExecutor)m_driver).executeScript("window.confirm = function(msg){return
true;};");

or if you want to click cancel:
((JavascriptExecutor)m_driver).executeScript("window.confirm = function(msg){return
false;};");

or if you want to handle an alert:
((JavascriptExecutor)m_driver).executeScript("window.alert = function(msg){};");

For my situation this seems like a fairly clean situation.  Sure I am overriding the
confirm/alert functions, so they won't handle quite like they would in a real
situation, but I always know before hand what button I want to press on a confirm box
and I really don't care about alert boxes.  Its not a perfect solution, I can't get
the actual message, but its easy and works for me.

Reported by ljarman0515@msn.com on 2009-08-11 17:44:12

@lukeis
Copy link
Member Author

lukeis commented Mar 2, 2016

Hi team, do you have an estimated resolution or implementation date of this issue?

Reported by edcruz90@hotmail.com on 2010-01-14 16:57:01

@lukeis
Copy link
Member Author

lukeis commented Mar 2, 2016

I've got a partial fix for the Selenium 1.0.1 version of this bug. With WebDriver and
Selenium merging, I thought I should post it here.

The basic idea is to use the onload event of the iframe containing the AUT to run the
selenium.browserbot._modifyWindow(window) function. 

This fix consists of two changes:
1. Change the RemoteRunner.html file so that this javascript appears in the header:

    function overrideMessageFunctions(iframe) {
        selenium.browserbot._modifyWindow(iframe.contentWindow);
    }

    function addHandler()
    {
        var element = window.document.getElementById('selenium_myiframe');
        var listener = function(){ overrideMessageFunctions(element);};
    if (element.addEventListener)
        element.addEventListener("load", listener, false);
    else
        element.attachEvent("onload", listener);
    }

2. In the AUT, change alert() to:
setTimeout(function(){alert();}, 0); 

This solution works in IE8 for sure, no reason why it shouldn't work for others as
well. Attached is the new RemoteRunner.html file.

Reported by wwiser on 2010-03-04 21:43:12


- _Attachment: [RemoteRunner.html](https://storage.googleapis.com/google-code-attachments/selenium/issue-27/comment-21/RemoteRunner.html)_

@lukeis
Copy link
Member Author

lukeis commented Mar 2, 2016

+1 for my vote!

As a workaround, this worked for me, though in my case I did not want a return value
as the modal dialog handled everything for the parent. Anyway thought I'd pass it on.

driver.executeScript("window.showModalDialog = window.openWindow;");

Reported by andrew.fawcett@coda.com on 2010-03-07 22:06:49

@lukeis
Copy link
Member Author

lukeis commented Mar 2, 2016

Will the resolution for this issue include support for file upload dialogs
(especially in RemoteWebDriver) as well, or should that be opened as a separate issue?

Reported by camoller on 2010-03-09 21:24:57

@lukeis
Copy link
Member Author

lukeis commented Mar 2, 2016

Currently using http://yarb.pl/post/505186243/confirming-javascript-alerts-in-capybara

to effectively stub out the alert/confirm calls.

Goes against the ideals, but it works!

Reported by keeran.beanlogic on 2010-04-26 16:10:02

@lukeis
Copy link
Member Author

lukeis commented Mar 2, 2016

Version: 2.0.0
Setup: Client/Server

Specific issue: Confirmation 

Server Setup:  
java -jar selenium-server-standalone-2.0.0.jar -role hub -host localhost -port 4444
Java –jar selenium-server-standalone-2.0.0.jar –role webdriver -hub http://localhost:4444/grid/register
-host localhost -port 5555 -browser browserName=firefox,version=3.6,maxInstances=3,platform=WINDOWS

Pom.xml:
<dependency>
  <groupId>org.seleniumhq.selenium</groupId>
  <artifactId>selenium-java</artifactId>
  <version>2.0.0</version>
  <scope>test</scope>
</dependency>

Java Client Setup:
DesiredCapabilities capability = DesiredCapabilities.firefox();
capability.setPlatform(Platform.WINDOWS);
capability.setVersion("3.6");
WebDriver webDriver = new RemoteWebDriver(new URL("http://localhost:4444/wd/hub" capability);
Selenium selenium = new WebDriverBackedSelenium(webDriver, "http://localhost:8080/portal");

// Code being used
public String getConfirmation() {
   String message;
   try {
      Alert alert = webDriver.switchTo().alert();
      message = alert.getText();
      alert.accept();
   } catch (final WebDriverException e) {
      message = null;
   }
   return message;
}

Description: Running the test, the javascript confirmation popup never appears and
the message retuned is null. But manually repeating the test it does appear.

Running the same automated test against FF4 or FF5, the popup appears and the message
is returned correctly.

Reported by slamacchia on 2011-07-27 06:24:18

@lukeis
Copy link
Member Author

lukeis commented Mar 2, 2016

I have this working without problem, Selenium 2.2, Firefox 3.6.15:

  driver.get("http://www.echoecho.com/samplecookie1.htm");
  Alert prompt = driver.switchTo().alert();
  WebDriver.Options driverOptions = driver.manage();
  driverOptions.addCookie( new Cookie("testCookie","BBB") );
  //waitSeconds(1);
  out.println(prompt.getText());
  prompt.sendKeys("AAA");
  //waitSeconds(1);
  prompt.accept();
  //waitSeconds(2);
  Set<Cookie> cookies = driverOptions.getCookies();
  for(Cookie cookie : cookies) 
  {out.println("COOKIE: " + cookie.getName() + ", " + cookie.getValue() ); }


Reported by rostislav.matl on 2011-07-28 15:00:34

@lukeis
Copy link
Member Author

lukeis commented Mar 2, 2016

Alerts work for java FirefoxDriver 2.3.0, but not for IE 8 nor Chrome on XP. Sorry,
this should be made critical issue as alert messages are basic functionality of any
web page. I had to use workaround with javascript as in comment #78 and it works but
it's not pretty http://code.google.com/p/selenium/issues/detail?id=27#c78
Also, driver.switchTo().alert() should return null, not throw Exception. The problem
is that many times it does not even get to this statment if you have driver.submit()
and javascript validation code that results in alert window and execution hangs on
submit until one clicks on ok button. The work around in #78 works for that scenario,
so before submit alert needs to be disabled and after enabled. 

Reported by bogdanz on 2011-08-03 08:16:59

@lukeis
Copy link
Member Author

lukeis commented Mar 2, 2016

Am I right to think that there is not any way to handle JS alerts invoked in page onload?
Such alerts hang up an WebDriver and tests are stopped.

Reported by sergey.safonov@sperasoft.com on 2011-08-26 08:10:42

@lukeis
Copy link
Member Author

lukeis commented Mar 2, 2016

@99: At the moment, yes

Reported by dawagner on 2011-08-26 17:00:15

@lukeis
Copy link
Member Author

lukeis commented Mar 2, 2016

Any way to handle windows security popups? alert.SendKeys() can send strings to user
name textbox, but cannot send special keys like TAB or ENTER. And alert.Accept() does
not work either, with an exception saying something like "could not find OK button"...

Reported by ztq121121 on 2011-09-01 12:36:57

@lukeis
Copy link
Member Author

lukeis commented Mar 2, 2016

when calling Selenium::WebDriver.get to load a page with an alert, while debuging i
noticed the application hangs until a timeout is reached. Then it just throws an error.
If I can suggest anything, an event callback should be implemented: driver.onAlert
= myAlertHandler, etc. As opposed to injecting some JavaScript wich apparently only
works in some cases. On the other hand calling Selenium::WebDriver.navigate.to instead
went over to the next call in the stack wich game me hope but then when calling driver.switch_to.alert.dismiss
, it hung again untill the thrown timeout error. im using a java remote server and
selenium webdriver 2.5.0. with firefox.

Reported by amatp1 on 2011-09-12 23:49:30

@lukeis
Copy link
Member Author

lukeis commented Mar 2, 2016

All drivers, to some degree, now support JS alerts and prompts. There are other issues
to do with security dialogs and similar, but those are different from this. Closing
this issue.

Reported by simon.m.stewart on 2011-11-22 17:50:53

  • Status changed: Fixed

@lukeis
Copy link
Member Author

lukeis commented Mar 2, 2016

Is this not fixed for chrome driver? From where I can download the new driver?

Reported by Chayanda04 on 2011-11-28 14:57:51

@lukeis
Copy link
Member Author

lukeis commented Mar 2, 2016

I was using this command when using require 'test/unit'

$b.confirm(true) do
      $b.button(:value,"reload").when_present.fire_event'onclick' # Reset the Database
end

It works perfectly in that case to handle the java script pop up which come up when
I click on the button named "reload"..

now I have switched to using require "rspec" instead and some how if now I use the
same command I get following error

 undefined method `confirm' for nil:NilClass

could some one help me in fixing it

Reported by ankita.gupta@adslot.com on 2012-03-27 05:44:07

@lukeis
Copy link
Member Author

lukeis commented Mar 2, 2016

This doesn't seem to be fixed. Not even close!!! I would recommend re-opening this issue.....

PS, it seems that just clicking something which causes a modal dialog to appear also
causes issues.

Reported by DocterJ208 on 2012-08-28 21:51:28

@lukeis
Copy link
Member Author

lukeis commented Mar 2, 2016

The title of this issue is rather broad.  It was mentioned in this thread about handling
alerts that occur in the onload of a page.  Is it possible to handle that scenario
with WebDriver?  If not can a new issue be opened for that specific issue?

Reported by JimRAnderson on 2013-01-22 20:23:00

@lukeis
Copy link
Member Author

lukeis commented Mar 2, 2016

@JimRAnderson WebDriver already supports this. There are tests in the WebDriver test
suite that test this[1], and the project's CI server[2] executes them for every commit.

[1] http://code.google.com/p/selenium/source/browse/java/client/test/org/openqa/selenium/AlertsTest.java#333
[2] http://ci.seleniumhq.org:8080/

Reported by james.h.evans.jr on 2013-01-22 21:05:37

@lukeis
Copy link
Member Author

lukeis commented Mar 2, 2016

I am getting modalwindow error,when i click a button.Alert is getting suppressed.
It stays for few seconds and modalWindow Exception comesUp.

Reported by imrank2112 on 2013-04-24 10:41:43

@lukeis
Copy link
Member Author

lukeis commented Mar 2, 2016

Refer to the above Post.Attaching the Exception

Reported by imrank2112 on 2013-04-24 10:46:58


- _Attachment: AlertIssue.png
![AlertIssue.png](https://storage.googleapis.com/google-code-attachments/selenium/issue-27/comment-111/AlertIssue.png)_

@lukeis
Copy link
Member Author

lukeis commented Mar 2, 2016

You should try to update before posting an issue/adding to an existing one. v2.25 is
rather old.

Reported by arran.huxtable on 2013-04-24 11:08:52

@lukeis
Copy link
Member Author

lukeis commented Mar 2, 2016


 WebElement actions =driver.findElement(By.id("actions"));
((JavascriptExecutor)driver).executeScript("arguments[0].click();" ,actions);


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

 the alert is 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. 


Reported by anilkumarcr1988 on 2013-12-04 06:06:06

@lukeis
Copy link
Member Author

lukeis commented Mar 2, 2016

pls anybody help me in fixing the above

Reported by anilkumarcr1988 on 2013-12-04 06:08:38

@lukeis
Copy link
Member Author

lukeis commented Mar 2, 2016

The confirm box is not accepted when using ChromeDriver in the scenario bellow:

Have a web page (2.html) that opens a new web page (3.html) where a confirm box is
shown onLoad event.

This works great with IE & Firefox but not with Chrome Driver - the confirm box stays
unclosed and I have exception that is not presented.

Find attached archive with sample test pages and explanation of the scenario.

Regards

Reported by zhelewnikolay on 2014-01-21 15:33:37


- _Attachment: [test.rar](https://storage.googleapis.com/google-code-attachments/selenium/issue-27/comment-116/test.rar)_

@lukeis
Copy link
Member Author

lukeis commented Mar 2, 2016


my requirement is 

->entering user id 
->entering password
->clicking on login button 
->if any one already login with same user id a popup message appears saying "already
login with same user id"  
->clicking ok on popup
->entering password 
->click on "continue anyway" link

i able to accept popup message but how to write code in Java - webdrier when click
on login button user should able to login but when popup message appears it should
able to accept popup message and then click on "continue any way link 


code  

    driver.findElement(By.id("txtUserId")).click();
    driver.findElement(By.id("txtUserId")).sendKeys("prakashm");
    driver.findElement(By.id("txtPwd")).clear();
    driver.findElement(By.id("txtPwd")).sendKeys("cmc123");
    driver.findElement(By.id("btnLogin")).click();
    Alert alert = driver.switchTo().alert();
    alert.accept()
    driver.findElement(By.id("txtPwd")).clear();
    driver.findElement(By.id("txtPwd")).sendKeys("cmc123");
    driver.findElement(By.id("hlkReLogin")).click();




Reported by nandaselenium on 2014-05-14 07:00:00

@lukeis
Copy link
Member Author

lukeis commented Mar 2, 2016

Hello,
I use Selenium 2.42.0 with Java and I need to use as WebDriver a headless browser like
HtmlUnit or PhantomJS. It`s important that I can handle alert which i trigger on purpose
for testing. I may close the Alert but I need to recognize it somehow in eclipse that
there has been an Alert, like getting the Text of the alert or even an Exception that
there is a alert present. 
 With this javascript i can only close the alert without recognition that there was
an alert:
 if (!(driver instanceof HtmlUnitDriver)) {
            System.out.println("test");
            ((JavascriptExecutor) driver).executeScript("window.alert = function(msg) { 
return true; }");
            ((JavascriptExecutor) driver).executeScript("window.confirm = function(msg) {
return true; }");
            ((JavascriptExecutor) driver).executeScript("window.prompt = function(msg) {
return true; }");
            }


Please is there any possibility just to recognize the alert in eclipse with java and
HtmlUnit or PhantomJs with Selenium!!

Reported by juzwa@gmx.net on 2014-06-24 12:52:23

@lukeis
Copy link
Member Author

lukeis commented Mar 2, 2016

Hi,

I am using selenium web driver ruby.I want to click on java script alert message (enter
key) using ruby command.
Please provide me the solution.

Reported by himanshutirodkar on 2014-07-28 06:19:57

@lukeis
Copy link
Member Author

lukeis commented Mar 2, 2016

You can use the following code to check whether Alert is present

public boolean isAlertPresent() 
{ 
    try 
    { 
        driver.switchTo().alert(); 
        return true; 
    }   // try 
    catch (NoAlertPresentException Ex) 
    { 
        return false; 
    }   // catch 
}   // isAlertPresent()

Reported by himanshu.parashar on 2015-02-27 17:05:46

@lukeis
Copy link
Member Author

lukeis commented Mar 2, 2016

Hi,
   I am using Selenium Web Driver. In there I can not handle pop up that is displayed
after login in New Window. Please Suggest me...

Note ..I have also attach regarding issue.

Reported by niteshkmr049 on 2015-04-06 12:15:35


- _Attachment: look.png
![look.png](https://storage.googleapis.com/google-code-attachments/selenium/issue-27/comment-121/look.png)_

@lukeis
Copy link
Member Author

lukeis commented Mar 2, 2016

Nitesh

The pop up you are dealing with looks like a html type of pop up, thus, it is built
with HTML & javascript. If it is so then you will have to build your own detection
code for it. You should be able to do it rather easily by checking if the pop up element
is present or has certain class.

Reported by eemeli.palotie on 2015-09-11 11:56:43

@lukeis
Copy link
Member Author

lukeis commented Mar 2, 2016

Reported by luke.semerau on 2015-09-17 17:47:52

  • Labels added: Restrict-AddIssueComment-Commit

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Projects
None yet
Development

No branches or pull requests

1 participant