WatiN, the web application automation tool, can easily handle dialog boxes. Here we show how to handle an alert dialog on the great resource that is Paul’s Online Math Notes.
On the homepage of Paul’s Online Math Notes there is a table on the left-hand side, the first cell of which contains the text ‘n/a’ and a hyperlink:
We want to automate the process of clicking on this link and then clicking on the Ok button in the resulting alert dialog:
The HTML for the cell we want to click on is:
Create a Console Application named “WatinDemo3” as in the post Getting Started with WatiN (Part 1) and paste the following code into “Program.cs”
using System; using System.Collections.Generic; using System.Linq; using System.Text; using WatiN.Core; using WatiN.Core.DialogHandlers; namespace WatinDemo3 { class Program { [STAThread] static void Main(string[] args) { IE browser = new IE(); // maximise the window browser.ShowWindow(WatiN.Core.Native.Windows.NativeMethods.WindowShowStyle.Maximize); browser.GoTo("http://tutorial.math.lamar.edu/"); // wait for page to load browser.WaitForComplete(); // create a dialog handler and add to browser AlertDialogHandler handler = new AlertDialogHandler(); browser.AddDialogHandler(handler); // find the table cell (<td> tag) containing the text '-n/a' TableCell tableCell = browser.TableCell(Find.ByText("-n/a-")); // get all the links in the table cell and click on the first one (index 0) // Using .Click() will fail as WatiN will wait indefinitely for something to happen within the browser tableCell.Links[0].ClickNoWait(); // wait until the alert dialog appears handler.WaitUntilExists(); // click on the Ok button handler.OKButton.Click(); // tidy up browser.RemoveDialogHandler(handler); browser.Close(); } } }
Note that WatiN allows us to find both the table cell and the link it contains without using their ids.
Try turning off the pop-up blocker if you have difficulties getting this program to run.