简体   繁体   English

如何在Selenium WebDriver中处理间歇性警报?

[英]How to handle intermittent alert in Selenium WebDriver?

I have automation scenario that sometimes the system return javascript alert and sometimes not at all. 我有自动化场景,有时系统返回javascript警报,有时根本不返回。 I don't know what the cause of this, probably the network issue. 我不知道是什么原因,可能是网络问题。 I already create the alert handler for this: 我已经为此创建了警报处理程序:

public boolean isAlertPresent() {
    WebDriverWait wait = new WebDriverWait(driver, 5);
    wait.until(ExpectedConditions.alertIsPresent());
    return true;
}

I call this in one of my step that sometimes appear alert: 我在我的一个步骤中称之为有时出现警报:

public WSSPage enterAndSearchContent(String title) throws InterruptedException {
    waitForElementTextWithEnter(searchTextField, title);
    while (isAlertPresent()){
        Alert alert = driver.switchTo().alert();
        alert.dismiss();
        break;
    }
    return PageFactory.initElements(driver, WSSPage.class);
}

The problem is when the alert doesn't show up, it will give me NoAlertPresentException, and the automation result will be failed. 问题是当警报没有显示时,它会给我NoAlertPresentException,并且自动化结果将失败。 I want the code to move on if the alert doesn't happen by moving to the next line, in this case it will just return PageFactory.initElements(driver, WSSPage.class); 如果通过移动到下一行没有发生警报,​​我希望代码继续前进,在这种情况下,它将只返回PageFactory.initElements(driver, WSSPage.class); Can you help me provide a better code from this? 你能帮我提供更好的代码吗? Thanks a lot. 非常感谢。

JavascriptExecutor worked for you. JavascriptExecutor为你工作。 Just take care that you should execute it before clicking the event which invoke alert. 在单击调用警报的事件之前,请务必执行它。

((JavascriptExecutor) driver).executeScript("window.confirm = function(msg) { return true; }");

Note :- do not use it after clicking on event which invoke alert confirmation box. 注意: - 点击调用警报确认框的事件后不要使用它。 Above code by default set the confirmation box as true means you are accepting/click on ok on all confirmation box on that page if invoked 默认情况下,上面的代码将确认框设置为true表示如果调用,则表示您接受/单击该页面上所有确认框中的确定

Hope it will help you :) 希望它能帮到你:)

You can modify the method isAlertPresent as given below and try it. 您可以修改方法isAlertPresent,如下所示并尝试。 It may help you. 它可能会帮助你。

public boolean isAlertPresent() {
    try{
       WebDriverWait wait = new WebDriverWait(driver, 5);
       wait.until(ExpectedConditions.alertIsPresent());
       return true;
    }
    catch (NoAlertPresentException noAlert) {
      return false;
    }
    catch (TimeoutException timeOutEx){
      return false;
    }
}

You can include that particular exception in try catch. 您可以在try catch中包含该特定异常。 Then the exception will be catched and will not through any error and your execution will continue. 然后将捕获异常,并且不会通过任何错误,您的执行将继续。 Also create a implicit wait to handle this with less timestamp. 还可以使用较少的时间戳创建隐式等待来处理此问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM