【问题标题】:WatiN Handle Confirm dialog in FirefoxFirefox 中的 WatiN 句柄确认对话框
【发布时间】:2011-04-13 22:01:52
【问题描述】:

我在 SO 上发现此代码可以自动关闭确认对话框,但它在 Firefox 中不起作用。

问题是,var windowButton = new WindowsEnumerator().GetChildWindows(window.Hwnd, w => w.ClassName == "Button" && new WinButton(w.Hwnd).Title == "OK").FirstOrDefault();

总是返回空值。有没有其他方法可以在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);
 }
}

【问题讨论】:

    标签: c# automation window watin


    【解决方案1】:

    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() 对话框中单击 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获得

    【讨论】:

    • firefox 类似乎没有 NativeDialog 属性。请指教。
    • 不,它没有。我的意思是 NativeDocument。我已经编辑了我的答案。
    • K,那里不存在 ClientPort。运行脚本()?
    • 不,您必须将其转换为 FFDocument。您确实应该查看具有更完整实现的链接。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-09-26
    • 2011-11-04
    • 2011-08-01
    • 2020-10-15
    • 2014-05-06
    • 2016-10-08
    • 2012-02-23
    相关资源
    最近更新 更多