我在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);
}
}
答案 0 :(得分:4)
Firefox警报()对话框中的控件不可枚举。也就是说,它们不像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点击警告()或确认()对话框上的“确定”和“取消”按钮。
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()处理,并在http://pastebin.com/ZapXr9Yf提供了Firefox处理