问题描述
|
我在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中那样作为单独的窗口存在。解决此问题的最佳方法是创建一个实现
IDialogHandler
的新DialogHandler
类。在构造函数中,您可以传入出现对话框的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在alert()或Confirm()对话框上单击“确定”和“取消”按钮。
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\";
http://pastebin.com/ZapXr9Yf提供了更完整的实现,该实现将本机IE alert()和Confirm()处理包装在一个通用界面中,并添加了Firefox处理。