Julian Jelfs’ Blog

WatiN Javascript Alert Dialog Handler

Posted in Unit Testing, WatiN by julianjelfs on October 7, 2011

The javascript alert handler that comes with WatiN out of the box didn’t quite do what I wanted. I needed something that could be automatically running the whole time and dismiss the alert whenever it happens but notify my code that the alert had happened and what the alert message had been. So I came up with the following modification to the WatiN version which suits my purpose:

    public class JavaScriptAlertDialogHandler : BaseDialogHandler
    {
        private readonly Action _onAlert;

        public JavaScriptAlertDialogHandler(Action onAlert)
        {
            _onAlert = onAlert;
        }

        public override bool HandleDialog(Window window)
        {
            if (CanHandleDialog(window))
            {
                _onAlert(window.Message);
                new WinButton(GetOKButtonId(), window.Hwnd).Click();
                return true;
            }
            return false;
        }

        public override bool CanHandleDialog(Window window)
        {
            return (window.StyleInHex == "94C801C5" && !ButtonWithId1Exists(window.Hwnd));
        }

        private static int GetOKButtonId()
        {
            return 2;
        }

        protected static bool ButtonWithId1Exists(IntPtr windowHwnd)
        {
            var button = new WinButton(1, windowHwnd);
            return button.Exists();
        }
    }

So when you construct the handler you pass in an Action that will receive the text of the message when the handler handles an alert e.g.

    IE.AddDialogHandler(new JavaScriptAlertDialogHandler(s => ScriptAlert = s));

Hope this is of some use to someone else too …

Advertisements
Tagged with:

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: