Ray Cheng
Ray Cheng

Reputation: 12576

How to click on OK button on Confirm box?

I'm testing an ASP.NET web form application. For IE, when I close the browser, a Confirm box pops up and I need to click on the OK button with Selenium Web Driver.

The JavaScript that pops up the box is:

<script type="text/javascript"> 
    //<![CDATA[
    function onBeforeUnloadAction() {return 'Are you sure to leave ALNW? All unsaved data will be discarded.';}
    window.onbeforeunload = function () {if ((window.event.clientX < 0) || (window.event.clientY < 0)) {return onBeforeUnloadAction();}}
    //]]>
</script>

The code to handle the Confirm box is:

driver.Close();
var alert = driver.SwitchTo().Alert();
alert.Accept();

The problem is the Confirm box just sitting there and the test fails. I do get the following exception at driver.Close():

Modal dialog present (UnexpectedAlertOpen)

EDIT

My workaround for now is to set the event handler to null and assume OK is clicked.

var js = driver as IJavaScriptExecutor;
js.ExecuteScript("window.onbeforeunload=null;");
driver.Close();

Upvotes: 1

Views: 1518

Answers (3)

Abhishek_Mishra
Abhishek_Mishra

Reputation: 4621

If it is a confirm box that comes through browser window not through your javascript code,Then you will not be handle it as an alert.Fot that purpose you need to go through any third party tool like autoit.

Here you can write a 4 to 5 line script to handle that confirm box and calling that script before the appearance of that confirm box.

Upvotes: 1

JimEvans
JimEvans

Reputation: 27486

The problem you're seeing is because the dialog presented by the onBeforeUnload event is not the same as a JavaScript confirm() dialog. Unfortunately, it's extremely difficult to distinguish between these two buttons on this particular dialog at the Windows API level. Unlike in a regular message box (which the JavaScript confirm() dialog is), these buttons do not have control IDs, nor is it safe to simply identify them by order or caption. If you discover a way to fix it, the maintainer of the IE driver would welcome a patch.

Upvotes: 1

Francis P
Francis P

Reputation: 13655

Using Selenium, record a test where you close that confirm box and then check what selenium used.

To adapt your code to Firefox:

<script type="text/javascript">
    var posx;var posy;
    function getMouse(e){
       posx=0;posy=0;
       var ev=(!e)?window.event:e;//IE:Moz
       if (ev.pageX){//Moz
          posx=ev.pageX+window.pageXOffset;
          posy=ev.pageY+window.pageYOffset;
       }
       else if(ev.clientX){//IE
          posx=ev.clientX+document.body.scrollLeft;
          posy=ev.clientY+document.body.scrollTop;
       }
       else{
          return false
       }//old browsers
       document.getElementById('myspan').firstChild.data='X='+posx+' Y='+posy;
    }
    document.onmousemove=getMouse
</script>

So reuse posx and posy in your onBeforeUnloadAction() function.

Upvotes: 1

Related Questions