WatiN处理确认对话框在Firefox
本文关键字:Firefox 对话框 确认 处理 WatiN | 更新日期: 2023-09-27 17:49:52
我在SO上发现这段代码可以自动取消确认对话框,但它在Firefox中不起作用。
问题是,var windowButton = new WindowsEnumerator().GetChildWindows(window.Hwnd, w => w.ClassName == "Button"
&& new WinButton(w.Hwnd).Title == "OK").FirstOrDefault();
总是返回null。是否有其他方法可以在firefox中获得对话框按钮的句柄?
public class OKDialogHandler : BaseDialogHandler {
public override bool HandleDialog(Window window) {
var button = GetOKButton(window);
if (button != null) {
button.Click();
return true;
} else {
return false;
}
}
public override bool CanHandleDialog(Window window) {
return GetOKButton(window) != null;
}
private WinButton GetOKButton(Window window) {
var windowButton = new WindowsEnumerator().GetChildWindows(window.Hwnd, w => w.ClassName == "Button"
&& new WinButton(w.Hwnd).Title == "OK").FirstOrDefault();
if (windowButton == null)
return null;
else
return new WinButton(windowButton.Hwnd);
}
}
Firefox alert()对话框中的控件是不可枚举的。也就是说,它们不像IE那样作为单独的窗口存在。最好的方法是创建一个新的DialogHandler
类来实现IDialogHandler
。在构造函数中,可以传入出现对话框的Firefox实例,并且可以使用以下代码将JavaScript发送到Firefox以操纵对话框:
FFDocument nativeDoc = firefox.NativeDocument as FFDocument;
// ClientPort has several WriteAndRead... functions,
// and takes a variable list of arguments for the script
// to be executed.
nativeDoc.ClientPort.WriteAndRead(script);
您可以使用下面的JavaScript来单击警报()或确认()对话框中的OK和Cancel按钮。
private const string DialogIsConfirmScript = "typeof getWindows()[{0}].document.documentElement.getButton('accept') !== 'undefined' && typeof getWindows()[{0}].document.documentElement.getButton('cancel') !== 'undefined';";
private const string DialogIsAlertScript = "typeof getWindows()[{0}].document.documentElement.getButton('accept') !== 'undefined' && typeof getWindows()[{0}].document.documentElement.getButton('cancel') !== 'undefined' && getWindows()[{0}].document.documentElement.getButton('cancel').hidden;";
private const string ClickCancelButtonScript = "getWindows()[{0}].document.documentElement.getButton('cancel').click()";
private const string ClickOKButtonScript = "getWindows()[{0}].document.documentElement.getButton('accept').click()";
private const string WindowClassName = "MozillaDialogClass";
一个更完整的实现,将本地IE alert()和confirm()处理封装在一个公共接口中,并添加Firefox处理,可以在http://pastebin.com/ZapXr9Yf