TopMenu

How to Fix Selenium popup alerts problem in Web Automation Testing

Selenium is popular framework that is being used with automation testing of webpages. But there is a problem that is being faced by the testing teams is it doesn’t support the handling of Popup or alert() boxes being called on onload() or onbeforeunload() event of browser. There’s workarounds exists like AutoIT etc. Special case seen for this is when we have Confirmation applied before navigating away from a page and selenium would fail to handle this and Automation will fail. One of my colleague was facing the same problem and he don’t want to use AutoIT. So I came with my own solution that can be used as fix and work well in handling the popups/alerts.

Environment: NUnit, Selenium, C#

The best way to deal with such alert box or popup is to use vbscript. It can identify the running window instance by its title and will send the “Enter” key to send ok.

The complete code for vbs will be:


Set oShell = CreateObject("WScript.Shell")
Set
args = WScript.Arguments
arg1 = args.Item(0)

If oShell.AppActivate(arg1) Then
Wscript.Sleep 500
oShell.SendKeys
"{ENTER}"
End
If

Create a new vbs file copy & paste the above code save it.

Next step is to call the vbs file when you webpage is showing the alert/popup with ok/cancel (whatever) buttons. To call the vbs you need to change your methods calls in NUnit.

So create a function that can call the vbs as separate process asynchronously to open and wait for a while to open the page and alert box to appear. Copy and paste the below method code. The function will take title of the window as argument and call the vbs file. I’ve named the vbs file to auto.vbs here.

public Thread SimulateClickForConfirmation(string title)
{

//Simulate autoclick on IE windows
Thread th = new Thread(new ThreadStart
(() => {
Thread
.Sleep(1000);
Process script = new Process
();
script.StartInfo.FileName =
Environment.CurrentDirectory + "\\auto.vbs"
;
script.StartInfo.Arguments = title;
script.Start();
script.WaitForExit();
script.Close();
}));

th.Start();

return th;
}

Now you’ll call this function when you want to simulate the click for the alert or confirmation popup.

for e.g:

Thread th = pObj.SimulateClickForConfirmation(currentPage.Title);

//navigating away from the current page by clicking through selenium
selenium.Click(Someotherpage);

//abort the thread if previous statement gets executed
th.Abort();

This will activate the browser window and click on the alerts or confirmation box’s default button. I hope this would help our testing team facing such problems.

So Don’t stop testing.. Smile.

2 comments:

  1. Can anyone give the solution using java

    ReplyDelete
  2. It is a one of the great discussion which is very essential for me as well. I must follow the handy discussion and sure that the content will be very useful to me as well. Keep it up.
    exit intent

    ReplyDelete